python2dnested-liststriangular

How to code a two dimensional triangular list in python with the formula of i**2 + j**2?


I am trying to solve this practice problem.

a) Prompt the user to enter a value of n = positive integer

b) Allocate a 2d triangular list with n rows, first row has length 1, second row has length 2, etc, last row has length n

c) Write nested loops = outer loop and inner (nested) loop to iterate over all the elements in the 2d list. If the loop counter for the outer loop is i and loop counter for the inner (nested) loop is j, set the values of the array elements to i^2 + j^2

d) Print the list to the console so that the display looks like this

0

1 2

4 5 8

9 10 13 18

16 17 20 25 32

25 26 29 34 41 50

etc

This is what I have done so far.

n = int(input("Please enter a positive integer for n: "))
while n <= 0:
    n = int(input("Error: Please enter a positive integer for n: "))
for i in range(n):
    for j in range(i + 1):
        print(i**2 + j**2)

I haven't been able to figure out how to make the triangular shape. I know it's suppose to use lists but I haven't gotten it yet. If anyone has any tips, it would be very helpful! Thank you!


Solution

  • Just follow the instructions...

    # a) prompt the user
    n = int(input("n: "))
    
    # b) allocate a 2d triangular list
    triangular = [ [0]*(i+1) for i in range(n) ]
    
    # c) nested loops...
    for i in range(n):
        for j in range(i+1):
            triangular[i][j] = i**2 + j**2
    
    # d) print the list
    for row in triangular: print(*row)
    

    Sample run:

    n: 5
    0
    1 2
    4 5 8
    9 10 13 18
    16 17 20 25 32