1

Please help. I need to create this pattern:

*
* $
* $ *
* $ * $
* $ * $ *
* $ * $
* $ *
* $
*
The best I can do is:
rows = 5
for i in range(0, 1):
    for j in range(0, i + 1):
        print("*", end=' ')
    print("\r")
for i in range(0, rows):
    for j in range(0, i + 1):
        d = "$"
        print("*",d, end=' ')
    print("\r")

for i in range(rows, 0, -1):
    for j in range(0, i - 1):
        print("*", d, end=' ')
    print("\r")

But it is not what I need. I desperately need help.

3 Answers 3

2

You cna simplify a bit : a loop for the increase from 1 to 4, another for the decrease from 5 to 1, then depend on odd/even values choose the correct symbol

rows = 5
for i in range(1, rows):
    for j in range(i):
        print('*' if j % 2 == 0 else "$", end=" ")
    print()

for i in range(rows, 0, -1):
    for j in range(i):
        print('*' if j % 2 == 0 else "$", end=" ")
    print()

Can be done in one outer loop

rows = 3
for i in range(-rows + 1, rows):
    for j in range(rows - abs(i)):
        print('*' if j % 2 == 0 else "$", end=" ")
    print()
Sign up to request clarification or add additional context in comments.

2 Comments

@BookishMass see shorten edit. Don't exagerate about your life haha, you can think about voting up and accept the answer ;)
range(-rows, rows) is clever but not quite right. Fix it with range(-rows + 1, rows).
1

Slightly different approach:

N = 5

result = []

for i in range(N):
    s = [('*', '$')[j % 2] for j in range(i+1)]
    result.append(s)
    print(*s)

for i in range(N-2, -1, -1):
    print(*result[i])

Comments

1

You can use the abs function to handle the inflection point with one loop:

print(
    *(
        ' '.join(
            '*$'[m % 2]
            for m in range(rows - abs(rows - n - 1))
        )
        for n in range(2 * rows - 1)
    ),
    sep='\n'
)

Or the above in one line, if you prefer:

print(*(' '.join('*$'[m % 2] for m in range(rows - abs(rows - n - 1))) for n in range(2 * rows - 1)), sep='\n')

Demo: https://replit.com/@blhsing/KnowledgeableWellwornProblem

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.