Skip to content

Instantly share code, notes, and snippets.

@phderome
Created November 28, 2018 02:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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]
@phderome
Copy link
Author

phderome commented Nov 28, 2018

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

@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