Skip to content

Instantly share code, notes, and snippets.

@internetimagery
Last active December 23, 2015 01:53
Show Gist options
  • Save internetimagery/39df361076b69b360273 to your computer and use it in GitHub Desktop.
Save internetimagery/39df361076b69b360273 to your computer and use it in GitHub Desktop.
Pascals triangle
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