Categories
Random

Pascals Triangle – python

Wrote a quick script that attempts to complete pascals triangle recursively, thanks Feng.
** Note, after getting some feedback made a number of changes, thanks Fry**
see source: pascals.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#########################################################
# Python Script: Pascals triangle #
# Enter How many rows you want... #
# Mark Culhane 2011, straightIT.com #
#########################################################

#Initialize
tri =[[1],[1]]
n = 0

def pascals():
if len(tri) rowNum = len(tri) - 1
colCnt = len(tri[rowNum])

if colCnt == rowNum:
tri[rowNum].extend([1])
tri.append([1])
else:
p1 = tri[len(tri)-2][len(tri[len(tri)-1])-1]
p2 = tri[len(tri)-2][len(tri[len(tri)-1])]
tri[rowNum].extend([p1+p2])
pascals()
return

def displaySol():
i = 0
for x in tri:
if i != n:
print(tri[i])
i = i + 1

if __name__ == "__main__":
print "Pascals Triangle"
n = long(raw_input("How many rows do you want?:"))
print "Result: "
pascals()
displaySol()

Leave a Reply

Your email address will not be published. Required fields are marked *