Categories

# 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

 12345678910111213141516171819202122232425262728293031323334353637 ######################################################### # 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()