5
\$\begingroup\$

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 :)

\$\endgroup\$
2
  • 1
    \$\begingroup\$I don't get how to use your pascal function. It just prints a bunch of generator expressions. Also, after the code has run, trying to call list(pascal_row(n)) with any n gives inconsistent behaviour. Try calling list(pascal_row(140)) followed by list(pascal_row(100)), followed by list(pascal_row(140)) again. The two results are completely different. Also, the list(pascal_row(100)) call returns [], which is obviously wrong.\$\endgroup\$
    – Graipher
    CommentedMar 21, 2017 at 10:26
  • \$\begingroup\$@Graipher Thanks for spotting so many errors for me! The inconsistency of pascal_row can be fixed by removing @lru_cache(), and I have to admit that my pascal function is wrong :(\$\endgroup\$
    – nalzok
    CommentedMar 21, 2017 at 10:43

1 Answer 1

5
\$\begingroup\$

If you look at the documentation for lru_cache you'll see that it says that it can save time when an expensive or I/O bound function is periodically called with the same arguments. You keep calling pascal_row with different arguments and the cache will miss all the time. This can be seen if you put this at the end of your program the line:

print(pascal_row.cache_info())

Output:

CacheInfo(hits=0, misses=500, maxsize=128, currsize=128)

The only other thing I'd say is that you don't really need the -*- coding: utf-8 -*- line, UTF8 is the default and that's what you're using anyway.

\$\endgroup\$

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.