Here is my implementation of a Pascal program, which is used to print an n-order Pascal triangle. This is actually an exercise I came up with to familiarize myself with Python's Functional Programming Modules.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import operator
from itertools import starmap, tee
from functools import lru_cache
def pairwise(iterable):
"""
s -> (s0,s1), (s1,s2), (s2,s3), ...
https://docs.python.org/3/library/itertools.html#itertools-recipes
"""
a, b = tee(iterable)
next(b, None)
return zip(a, b)
@lru_cache()
def pascal_row(n):
"""
Print the nth row of a Pascal triangle
"""
if n < 2:
return (x for x in [1])
else:
def dispatch():
yield 1
yield from starmap(operator.add, pairwise(pascal_row(n-1)))
yield 1
return dispatch()
def pascal(n):
"""
Print an n-order Pascal triangle
"""
for i in range(1, n):
print(pascal_row(i))
print([x for x in pascal_row(500)])
Is this the right way of functional programming? Also, I want you to tell me how to make this piece of code clearer :)
pascal
function. It just prints a bunch of generator expressions. Also, after the code has run, trying to calllist(pascal_row(n))
with any n gives inconsistent behaviour. Try callinglist(pascal_row(140))
followed bylist(pascal_row(100))
, followed bylist(pascal_row(140))
again. The two results are completely different. Also, thelist(pascal_row(100))
call returns[]
, which is obviously wrong. \$\endgroup\$pascal_row
can be fixed by removing@lru_cache()
, and I have to admit that mypascal
function is wrong :( \$\endgroup\$