Search code examples
pythonpascals-triangle

Pascal's triangle in python?


I seem to be having a problem with creating a pascal's triangle in python, and I'm really realyl frustrated not finding the problem. Please help. Thanks.

Heres the code:

inpt = input("Enter levels: ")   #number of levels in a triangle
list1 = []
list2 = [1]

for a in range(inpt):
    list1.append(1)
    for x in range(a+1):
        if (x == 0 or x == a):
            list1[x]
        elif (x > 0 or x < a):
            list1[x] = list2[x] + list2[x-1]
    print list1
    list2 = list1

and it prints something like this:

[1]
[1, 1]
[1, 2, 1]
[1, 3, 4, 1]
[1, 4, 8, 9, 1]

Solution

  • With list2 = list1 you are saying that the two names list1 and list2 are referencing the same list.
    To really copy the list, you can use list2 = list1[:] (or a module like copy. See also this question ("python list by value not by reference"))

    for a in range(inpt):
        list1.append(1)
        for x in range(a+1):
            if (x == 0 or x == a):
                list1[x]
            elif (x > 0 or x < a):
                list1[x] = list2[x] + list2[x-1]
        print list1
        list2 = list1[:]