BedroomLANTilde~A: Alexios' HomepageSearch |
![]() |
||
Pascal's Triangle in PythonYou need to generate Pascal's Triangle in Python, and you're lazy (an admirable trait). Alternatively, you're looking for a Pascal's Triangle generator that can show really high-ranking rows, ones with multi-hundred-digit (or multi-million-digit) coefficients. SolutionHere's the essential, unadorned code: def pascal(n): """ Yield up to row ``n`` of Pascal's triangle, one row at a time. The first row is row 0. """ def newrow(row): "Calculate a row of Pascal's triangle given the previous one." prev = 0 for x in row: yield prev + x prev = x yield 1 prevrow = [1] yield prevrow for x in xrange(n): prevrow = list(newrow(prevrow)) yield prevrow DiscussionIt all revolves around the auxilliary function The return value of Python generators are speedy beasts. On my desktop computer, In fact, ExtensionsThis version includes an example (and doctest), and checks the value of def pascal(n): """ Yield up to row ``n`` of Pascal's triangle, one row at a time. The first row is row 0. >>> list (pascal (0)) [ [1] ] >>> list (pascal (1)) [ [1], [1, 1]] >>> list (pascal (4)) [ [1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1] ] >>> list (pascal (-1)) Traceback (most recent call last): ValueError: n must be an integer >= 0 """ if not isinstance(n, int): raise TypeError('n must be an integer') if n < 0: raise ValueError('n must be an integer >= 0') def newrow(row): "Calculate a row of Pascal's triangle given the previous one." prev = 0 for x in row: yield prev + x prev = x yield 1 prevrow = [1] yield prevrow for x in xrange(n): prevrow = list(newrow(prevrow)) yield prevrow In all other aspects, this is identical to the first implementation. |
|
|
|
Recent comments
5 hours 35 min ago
7 weeks 6 days ago
8 weeks 3 days ago
17 weeks 5 days ago
18 weeks 6 days ago
19 weeks 6 days ago
21 weeks 4 days ago
22 weeks 23 hours ago
23 weeks 3 days ago
28 weeks 3 days ago