Think Python 2e by Allen Downey 📔

Intro

This a review of Think Python 2e by Allen Downey.

This book is divided into 21 chapters and is about 257 pages long

1 - Way of the program 🥋

2 - variables, expressions and statements ⚽

3 - functions

4 - interface design

5 - conditionals and recursion 🔁

6 - fruitful functions 🍓

7 - iteration 🔂

>>> x = 5
>>> x
5
>>> x = 7
>>> x
7
import math

def estimate_pi():
sum = 0
epsilon = math.pow(10, -15)
k = 0
i = 1 # initialize i, the value doesn't matter
while i > epsilon:
i = math.factorial(4 * k) * (1103 + 26390 * k) \
/ (math.pow(math.factorial(k), 4) * math.pow(396, 4 * k))
sum += i
k += 1
inverse = 2 * math.sqrt(2) * sum / 9801
return 1 / inverse


print (estimate_pi())
print (math.pi)
print (estimate_pi() - math.pi)

8 - strings 🧵

9 - word play

10 - lists

def add_all(t):
total = 0
for x in t:
total += x
return total
>>> t = [1, 2, 3]
>>> sum(t)
6

11 - dictionaries 📚

# memoized version of fibonacci

known = {0:0, 1:1}

def fibonacci(n):
if n in known:
return known[n]

res = fibonacci(n-1) + fibonacci(n-2)
known[n] = res
return res

12 - tuples 👨‍👨‍👧‍👧

>>> t = 'a', 'b', 'c'
>>> t
('a', 'b', 'c')

>>> u = 'a',
>>> u
('a',)
>>> a, b = b, a
>>> t = divmod(7, 3)
>>> t
(2, 1)
def printall(*args):
print(args)
>>> t = (7,3)
>>> divmod(*t) # scatter the tuple

13 - DS selection

14 - files 📂

15 - classes and objects

16 - classes and functions

17 - classes and methods

sketch(parrot, cage, dead=True)

18 - inheritance

19 - the goodies

y = math.log(x) if x > 0 else float('nan')
# without LC
def capitalize_all(t):
res = []
for s in t:
res.append(s.capitalize())
return res

# with LC
def capitalize_all(t):
return [s.capitalize() for s in t]
>>> g = (x**2 for x in range(5))
>>> any([False, False, True])
True
def has_duplicates(t):
return len(set(t)) < len(t)
from collections import Counter

def is_anagram(w1, w2):
return Counter(w1) == Counter(w2)

20 - debugging

21 - algorithm analysis


Conclusion

Overall I liked this book and recommend it to anyone who is interested in the Python programming language. It is written in an easy to read style, and the examples are quite manageable.