Creating triangle pattern in python looping two characters using nested loop

Question:

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.

Asked By: Bookish Mass

||

Answers:

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, rows):
    for j in range(rows - abs(i)):
        print('*' if j % 2 == 0 else "$", end=" ")
    print()
Answered By: azro

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])
Answered By: Stuart

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

Answered By: blhsing
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.