Skip to content

Instantly share code, notes, and snippets.

@phderome
Created November 28, 2018 02:36
Show Gist options
  • Save phderome/ef93705e3acffa852f782e28b86958db to your computer and use it in GitHub Desktop.
Save phderome/ef93705e3acffa852f782e28b86958db to your computer and use it in GitHub Desktop.
type-hinting-edge-case ch6ex1 FunctionalProgrammingInPythonV2
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]
@slott56
Copy link

slott56 commented Nov 28, 2018

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