# 日拱一卒，一起来上伯克利的实验课，带你入门Python

Github

inst.eecs.berkeley.edu//~cs61a/sp1…

## What Would Python Display (Part 1)?

### Q1: WWPD: Veritasiness

``````>>> True and 13
______

>>> False or 0
______

>>> not 10
______

>>> not None
______

>>> True and 1 / 0 and False
______

>>> True or 1 / 0 or False
______

>>> True and 0
______

>>> False or 1
______

>>> 1 and 3 and 6 and 10 and 15
______

>>> 0 or False or 2 or 1 / 0
______

>>> not 0
______

>>> (1 + 1) and 1
______

>>> 1/0 or True
______

>>> (True or False) and False
______

### Q2: WWPD: Loops

``````>>> n = 3
>>> while n >= 0:
...     n -= 1
...     print(n)
______

>>> n = 4
>>> while n > 0:
...     n += 1
...     print(n)
______

>>> def go(n):
...     if n % 2 != 0:
...         print(n / 2)
...         return
...     while n > 0:
...         print(n)
...         n = n // 2
>>> go(4)
______

>>> go(5)
______

>>> zero = 2
>>> while zero != 0:
...    zero = zero // 2
...    print(zero)
______

>>> positive = 28
>>> while positive:
...    print("positive?")
...    positive -= 3
______

>>> positive = -9
>>> negative = -12
>>> while negative:
...    if positive:
...        print(negative)
...    positive += 3
...    negative += 3
______

## Coding Practice

### Q3: Repeated

``````>>> def square(x):
...     return x * x
...
>>> repeated(square, 2, 3)  # square(square(3)), or 3 ** 4
81
>>> repeated(square, 1, 4)  # square(4)
16
>>> repeated(square, 6, 2)  # big number
18446744073709551616
>>> def opposite(b):
...     return not b
...
>>> repeated(opposite, 4, True)
True
>>> repeated(opposite, 5, True)
False
>>> repeated(opposite, 631, 1)
False
>>> repeated(opposite, 3, 0)
True
"""

#### 答案

``````def repeated(f, n, x):
"""Returns the result of composing f n times on x.
"""
if n == 1:
return f(x)
return f(repeated(f, n-1, x))

``````def repeated(f, n, x):
"""Returns the result of composing f n times on x.
"""
ret = x
for _ in range(n):
ret = f(ret)
return ret

### Q4: Sum Digits

``````>>> sum_digits(10) # 1 + 0 = 1
1
>>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12
12
>>> sum_digits(1234567890)
45

#### 答案

``````def sum_digits(n):
"""Sum all the digits of n.
"""
if n < 10:
return n
return sum_digits(n // 10) + n % 10

``````def sum_digits(n):
"""Sum all the digits of n.
"""
ret = 0
while n > 0:
ret += n % 10
n //= 10
return ret

### Q5: Double Eights

``````>>> double_eights(8)
False
>>> double_eights(88)
True
>>> double_eights(2882)
True
>>> double_eights(880088)
True
>>> double_eights(12345)
False
>>> double_eights(80808080)
False

#### 答案

``````def double_eights(n):
"""Return true if n has two eights in a row.
"""
return '88' in str(n)

``````def double_eights(n):
"""Return true if n has two eights in a row.
"""
while n > 10:
if n % 100 == 88:
return True
n //= 10
return False

``````def double_eights(n):
"""Return true if n has two eights in a row.
"""
if n < 10:
return False
pref, suff = (n % 100) // 10, n % 10
return (pref == 8 and suff == 8) or double_eights(n // 10)

# 附加题

## What Would Python Display (Part 2)?

### Q6: WWPD: Truthiness

``````>>> 0 or True
______

>>> not '' or not 0 and False
______

>>> 13 and False
______

>>> False or 1
______

>>> '' or 1 and 1/0
______

>>> not 0 and 12 or 0
______

### Q7: WWPD: What If?

``````>>> def xk(c, d):
...     if c == 4:
...         return 6
...     elif d >= 4:
...         return 6 + 7 + c
...     else:
...         return 25
>>> xk(10, 10)
______

>>> xk(10, 6)
______

>>> xk(4, 6)
______

>>> xk(0, 0)
______

>>> def how_big(x):
...     if x > 10:
...         print('huge')
...     elif x > 5:
...         return 'big'
...     elif x > 0:
...         print('small')
...     else:
...         print("nothin'")
>>> how_big(7)
______

>>> how_big(12)
______

>>> how_big(1)
______

>>> how_big(-1)
______

>>> def so_big(x):
...     if x > 10:
...         print('huge')
...     if x > 5:
...         return 'big'
...     if x > 0:
...         print('small')
...     print("nothin'")
>>> so_big(7)
______

>>> so_big(12)
______

>>> so_big(1)
______

>>> def ab(c, d):
...     if c > 5:
...         print(c)
...     elif c > 7:
...         print(d)
...     print('foo')
>>> ab(10, 20)
______

>>> def bake(cake, make):
...     if cake == 0:
...         cake = cake + 1
...         print(cake)
...     if cake == 1:
...         print(make)
...     else:
...         return cake
...     return make
>>> bake(0, 29)
______

>>> bake(1, "mashed potatoes")
______

## More Coding Practice

### Q8: Fix the Bug

``````def both_positive(x, y):
"""Returns True if both x and y are positive.

>>> both_positive(-1, 1)
False
>>> both_positive(1, 1)
True
"""
return x and y > 0 # You can replace this line!

### Q9: Falling Factorial

``````>>> falling(6, 3)  # 6 * 5 * 4
120
>>> falling(4, 0)
1
>>> falling(4, 3)  # 4 * 3 * 2
24
>>> falling(4, 1)  # 4
4

#### 答案

``````def falling(n, k):
"""Compute the falling factorial of n to depth k.
"""
ret = 1
for i in range(n, n-k, -1):
ret *= i
return ret

``````def falling(n, k):
"""Compute the falling factorial of n to depth k.
"""
if k == 0:
return 1
return n * falling(n-1, k-1)

## I Want to Play a Game

`guess_random`函数会让你先选一个数，然后循环你若干次它的猜测是否正确。如果它猜对了，输入`y`，否则输入`n`。Python并不擅长猜数，所以可能会猜很久，你可以通过`Ctrl-C`来终止程序。

### Q10: Guess Linear

`guess_random`策略的一个弱点就是它可能会重复猜测某些错误的数字，所以我们可以使用线性猜测让它更加合理。

``````def guess_linear():
"""Guess in increasing order and return the number of guesses."""
prompt_for_number(LOWER, UPPER)
num_guesses = 1
guess = LOWER
return num_guesses

#### 答案

``````def guess_linear():
"""Guess in increasing order and return the number of guesses."""
prompt_for_number(LOWER, UPPER)
num_guesses = 1
guess = LOWER
while guess <= UPPER:
correct = is_correct(guess)
if correct:
break
guess += 1
num_guesses += 1
return num_guesses

### Q11: Guess Binary

`is_too_high`的用法如下：

``````def guess_binary():
"""Return the number of attempted guesses. Implement a faster search
algorithm that asks the user whether a guess is less than or greater than
the correct number.

Hint: If you know the guess is greater than the correct number, then your
algorithm doesn't need to try numbers that are greater than guess.
"""
prompt_for_number(LOWER, UPPER)
num_guesses = 1
lower, upper = LOWER, UPPER
guess = (lower + upper) // 2
return num_guesses

### A Second Look

``````python3 guessing_game_graph.py guess_linear
python3 guessing_game_graph.py guess_binary