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 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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.