Write a nested for loop that displays the following outpout:

                   1
               1   2  1
            1  2   4  2  1
         1  2  4   8  4  2  1
       1 2  4  8  16  8  4  2 1
     1 2 4  8 16  32 16  8  4 2 1
   1 2 4 8 16 32  64 32 16  8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1

What I have so far is as follows:

for i in range(1, 8 + 1):
    for j in range(i, 0, -1):
        print(j),
    print("")

which outputs:

1
2 1
3 2 1
4 3 2 1 
5 4 3 2 1
6 5 4 3 2 1
7 6 2 4 3 2 1
8 7 6 5 4 3 2 1

Any guidance is appreciated.

To get you started:

for ctr in range(8):
    print 2**ctr,
for ctr in range(6, -1, -1):
    print 2**ctr,
print

for ctr in range(2):
    print 2**ctr,
for ctr in range(0, -1, -1):
    print 2**ctr,
print

for ctr in range(1):
    print 2**ctr,
for ctr in range(-1, -1, -1):
    print 2**ctr,
print

To print with all columns lined up correctly, you will have to calculate the final row first, or store all rows in a list, and then print according to the size of the number in the last row. For n rows, the last row will have n+(n-1) columns=8+7 for 8 rows. To place the 3rd row in the middle for example (3rd row contains 5 numbers), subtract the number from total available columns, 15-5=10. Divide by 2=5, which means row 3 would have 5 'empty' elements, then the 5 calculated elements=1, 2, 4, 2, 1, and then 5 more empty elements.

for i in range(1, 9):
    for i in range(-1+i, -1, -1):
        print(format(2**i, "4d")),


    print

I've gotten the right side of the pyramid, but can't seem to get the left.
Any suggestions?

Have developed the following:

for i in range(1, 9):

    for i in range(0,i,1):
        print(format(2**i, "4d")),

    for i in range(-1+i, -1, -1):
        print(format(2**i, "4d")),   



    print

Now, I am struggling with indentations.
Any suggestions?

for i in range(1, 9):


    n = 34-(5*(i-1))+1
    print(" ")*n,

    for i in range(0,i,1):
        print(format(2**i, "4d")),

    for i in range(-1+i, -1, -1):
        print(format(2**i, "4d")),   

    print
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.