Desired Pattern is this

USING THIS CODE
order = int(input("Enter the order : "))
c = ord("A")
d = 1
for i in range(order,0,-1):
for j in range(i):
print(" ",end=" ")
for k in range(1,d+1):
#c=c-1
print(chr(c),end=" ")
c=c+1
d=d+1
print()
I am getting this pattern:
A
B C
D E F
G H I J
Using the same approach, slightly changing your second inner loop and how you update c should work:
order = int(input("Enter the order : "))
c = ord("A")
d = 1
for i in range(order,0,-1):
for j in range(i):
print(" ",end=" ")
for k in range(0, d): # iter from 0 to number of letters in the row
print(chr(c - k),end=" ") # backtrack from starting letter
d=d+1 # increment d before updating c
c = c + d # update c to be the starting letter of the next row
print()
Returns
Enter the order : 4
A
C B
F E D
J I H G
When you print(chr(c)) you essentially need to reverse the direction c is moving since you want to print the letters in reverse order. This is easy enough and can be done with just a few extra lines.
First, c should start out at the last (alphabetically) ascii value for the character you want to print (on that specific line). This is done by saying c += d right before your for k for loop.
Then, since we're going backwards, we need to decrement c by 1 each time. We add c -= 1 at the very start of your for k loop.
Finally, we need to push c back to the next letter. Since we printed d letters, we just add c += d after the for k loop. This last bit might seem a bit confusing. As an example, one of the lines printed is J I H G. After printing this line, c has the ascii value of G but we want to be able to print the next letter after J and not G which is why we add the value of d again.
The completed code is
order = int(input("Enter the order : "))
c = ord("A")
d = 1
for i in range(order,0,-1):
for j in range(i):
print(" ",end=" ")
c += d
for k in range(d):
c -= 1
print(chr(c),end=" ")
c += d
d += 1
print()
Output:
Enter the order : 6
A
C B
F E D
J I H G
O N M L K
U T S R Q P
P.S
x = x + 1, it is more pythonic to say x += 1. This is the case for all the other mathematical operations. x = x*3 can be re-written as x *= 3. for k in range(1, d+1) can be written more succinctly as for k in range(d)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With