0

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]
edrichhans
  • 113
  • 1
  • 2
  • 11
  • What do you think is the problem? It's doing exactly what you ask it to - what should it be doing instead? Note that `list2 = list1` means both names reference *the same object*, which probably isn't what you want. – jonrsharpe Sep 02 '14 at 10:49

3 Answers3

4

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[:]
Community
  • 1
  • 1
fredtantini
  • 15,966
  • 8
  • 49
  • 55
1

You can simplify your code.

for x in range(a+1) starts at 0 and goes all the way to a because you are using a+1, you use if checks to avoid 0 and a so it would make more sense to start your range from 1 and loop over the range(a) thus removing the need for any if/elif checks:

for a in xrange(inpt):
    list1.append(1)
    for x in xrange(1, a):
        list1[x] = list2[x] + list2[x-1]
    print list1
    list2 = list1[:]
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
-1

I believe you need to deep copy or clone your lists instead of list2=list1 as this will make both variables point to the same list. Refer to How to clone or copy a list?

Community
  • 1
  • 1
Ranald Lam
  • 496
  • 4
  • 9