Home > database >  Creating triangle pattern in python looping two characters using nested loop
Creating triangle pattern in python looping two characters using nested loop

Time:08-01

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.

CodePudding user response:

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()

CodePudding user response:

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])

CodePudding user response:

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

  • Related