How to print pattern where each subsequent column is squared?

58 Views Asked by At

Here is the pattern I am trying to print:

1
2 4
3 9 27
4 16 64 256
5 25 125 625 3125

Here is what I have so far, and I am stuck at this point.

for rows in range(1,5+1):
    for columns in range(rows):
        columns= (rows)**rows
        print(columns , end=' ')
    print('')
3

There are 3 best solutions below

0
On BEST ANSWER

Try this

for rows in range(1,5+1):
for columns in range(1,rows+1):
    columns= (rows)**columns
    print(columns , end=' ')
print('')

You will need to take it as rows raised to columns. Output:

1 
2 4 
3 9 27 
4 16 64 256 
5 25 125 625 3125
0
On

This is how the code should be instead:

    for rows in range(1,5+1):
            for columns in range(rows):
                result = (rows)**columns
                print(result, end=' ')
            print('')

The result is then the one you were looking to have.

0
On

Simple, Just use another variable to hold the place of previous result and to multiply with current variable, don't forget to assign '1' at the end of inner loop or else the multiplication result will gets accumulated.

for rows in range(1, 5 + 1):
  mul = 1
  for columns in range(rows):
    mul = rows*mul
    print(mul, end = '\t')
  print('\n')

Output:

1   

2   4   

3   9   27  

4   16  64  256 

5   25  125 625 3125