anthonyceaser2021
anthonyceaser2021

Reputation: 51

Creating pascals triangle using recursion feature on python

I am creating code to give an output of pascals triangle using recursion specifically to create each level of Pascal's triangle, reaching the requested height.The code I am creating follows the conventional numbering of a Pascal’s triangle: the first row (the single 1 at the top) is row zero, meaning that a request for a triangle of height 5 will result in six rows being generated in total. My code so far uses recursion but it seems I have trouble using the user's integer to create a pascals triangle.

def pascal(choice):
    #if user enters 0 then return nothing
    if choice == 0:
        return []
    elif choice == 1:
        #using here list of lists using recursion now
        #if user enters 1 then return using 1 
        return [[1]]
    else:
        new_row = [1]
        result = pascal(choice-1)
        last_row = result[-1]
        for i in range(len(last_row)-1):
            # here I'm picking off the last elements of the list to build each new row
            new_row.append(last_row[i] + last_row[i+1])
        new_row += [1]
        result.append(new_row)
    return result

print("Welcome to the Pascal's triangle generator.")
choice=int(input("Please enter the number of levels to generate:"))
list=[]
print(list, choice)

pascal(choice)

Upvotes: 1

Views: 403

Answers (1)

Ben
Ben

Reputation: 46

You need to wrap your last line in a print statement.

To print it line by line you could use

triangle = pascal(n)
for line in triangle:
    print(line)

Upvotes: 1

Related Questions