Last active
December 23, 2015 01:53
-
-
Save internetimagery/39df361076b69b360273 to your computer and use it in GitHub Desktop.
Pascals triangle
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
import collections | |
class Pascals_Triangle(collections.Sequence): | |
""" Build a triangle as indexes are requested """ | |
tri = [(1,)] | |
def __len__(s): return len(s.tri) | |
def __repr__(s): | |
rows = [repr(a) for a in s.tri] | |
size = max(len(a) for a in rows) | |
return "\n".join(a.center(size) for a in rows) | |
def next_row(s, last_row): | |
yield 1 | |
for i in range(len(last_row) -1): | |
yield last_row[i] + last_row[i + 1] | |
yield 1 | |
def __getitem__(s, n): | |
while n >= len(s.tri): | |
type(s).tri.append(tuple(s.next_row(s.tri[-1]))) | |
return s.tri[n] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment