defdouble_eights(n):
"""Return true if n has two eights in a row.
"*** YOUR CODE HERE ***"while n > 10:
if n % 100 == 88:
returnTrue
n //= 10returnFalse
基于上面迭代的方法,我们也可以写出递归的解法,本质上思路是一样的,只是代码实现略有不同。
defdouble_eights(n):
"""Return true if n has two eights in a row.
"*** YOUR CODE HERE ***"if n < 10:
returnFalse
pref, suff = (n % 100) // 10, n % 10return (pref == 8and suff == 8) or double_eights(n // 10)
>>> defxk(c, d):
... if c == 4:
... return6... elif d >= 4:
... return6 + 7 + c
... else:
... return25>>> xk(10, 10)
______
>>> xk(10, 6)
______
>>> xk(4, 6)
______
>>> xk(0, 0)
______
>>> defhow_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)
______
>>> defso_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)
______
>>> defab(c, d):
... if c > 5:
... print(c)
... elif c > 7:
... print(d)
... print('foo')
>>> ab(10, 20)
______
>>> defbake(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
下列代码片段有bug,找出其中的bug并修复
defboth_positive(x, y):
"""Returns True if both x and y are positive.
>>> both_positive(-1, 1)
False
>>> both_positive(1, 1)
return x and y > 0# You can replace this line!
完成之后进行测试:python3 ok -q both_positive
症结在于Python当中只有0是False,所以应该改成:return x > 0 and y > 0
defguess_linear():
"""Guess in increasing order and return the number of guesses."""
prompt_for_number(LOWER, UPPER)
num_guesses = 1
guess = LOWER
"*** YOUR CODE HERE ***"return num_guesses
很简单,一直猜测,直到猜对为止
defguess_linear():
"""Guess in increasing order and return the number of guesses."""
prompt_for_number(LOWER, UPPER)
num_guesses = 1
guess = LOWER
"*** YOUR CODE HERE ***"while guess <= UPPER:
correct = is_correct(guess)
if correct:
break
guess += 1
num_guesses += 1return num_guesses
defguess_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"*** YOUR CODE HERE ***"return num_guesses