Created
November 28, 2018 02:36
-
-
Save phderome/ef93705e3acffa852f782e28b86958db to your computer and use it in GitHub Desktop.
type-hinting-edge-case ch6ex1 FunctionalProgrammingInPythonV2
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
def fibi2(n: int) -> int: | |
"""Fibonacci numbers with iteration and memoization | |
>>> fibi2(20) | |
6765 | |
>>> fibi2(1) | |
1 | |
""" | |
# originally, line 109 had None (replace with Int as 0) f = [0, 1] + [None for _ in range(2, n+1)] | |
f = [0, 1] + [0 for _ in range(2, n+1)] | |
for i in range(2, n+1): | |
f[i] = f[i-1]+f[i-2] | |
return f[n] |
Interesting that PyCharm does more strict checking than mypy does.
An alternative is this:
f: List[Optional[int]] = [0, 1] + [None for _ in range(2, n+1)]
Which states that you'll have a mixture of int and None in the list.
This has the tiny advantage of not polluting the list with invalid numeric values. It uses None
for not-yet-computed.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
quoted from ch6ex1 of Functional Programming in Python Edn 2 by Steven Lott (Pakt Publisher)
Line 109 (shown here at line 9) had None and was replaced with 0 in gist (line 10).
Interestingly PyCharm plugin or IDE points to the typing problems highlighting the location of issue.
Discussing with author was useful to me in that I get a better sense of how typing usage becomes part of required work for Python development (I come from Scala background so using types is something I value naturally and find hard to do well).