Last active
December 27, 2015 20:48
-
-
Save animatedlew/7386780 to your computer and use it in GitHub Desktop.
An implementation of pascal's triangle in python. Please compare this to my implementation in Scala.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def pascal(r, c): | |
fac = lambda(num): (1 if (num < 1) else num*fac(num-1)) | |
return fac(r)/(fac(c)*fac(r-c)) | |
def pascal2(r, c): | |
return 1 if (c == 0 or c == r) else pascal2(r-1, c-1) + pascal2(r-1, c) | |
def triangle(totalRows, op): | |
def draw(op): | |
list = "" | |
for row in range(totalRows+1): | |
for space in range(totalRows-row): | |
list += " " | |
for col in range(row+1): | |
list += "{:^4}".format(op(row, col)) | |
list += "\n" | |
return list | |
return draw(op) | |
print(triangle(10, pascal)) | |
print(triangle(10, pascal2)) | |
''' | |
1 | |
1 1 | |
1 2 1 | |
1 3 3 1 | |
1 4 6 4 1 | |
1 5 10 10 5 1 | |
1 6 15 20 15 6 1 | |
1 7 21 35 35 21 7 1 | |
1 8 28 56 70 56 28 8 1 | |
1 9 36 84 126 126 84 36 9 1 | |
1 10 45 120 210 252 210 120 45 10 1 | |
1 | |
1 1 | |
1 2 1 | |
1 3 3 1 | |
1 4 6 4 1 | |
1 5 10 10 5 1 | |
1 6 15 20 15 6 1 | |
1 7 21 35 35 21 7 1 | |
1 8 28 56 70 56 28 8 1 | |
1 9 36 84 126 126 84 36 9 1 | |
1 10 45 120 210 252 210 120 45 10 1 | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment