Q1: Return and Print
写出print(welcome(), cal())和welcome()的结果。
def welcome():
print('Go')
return 'hello'
def cal():
print('Bears')
return 'world'
前者的结果如下:先打印后返回函数的结果。
print(welcome(), cal())
Go
Bears
hello world
后者的结果如下:
welcome()
Go
'hello'
⚠️注意:return是对函数的终止,print只是单纯地表示打印字符。
Q2: Debugging Quiz
此处未进行分析。参考debugging article即可作答。
Q3: Pick a Digit
def digit(n, k):
"""Return the digit that is k from the right of n for positive integers n and k.
>>> digit(3579, 2)
5
>>> digit(3579, 0)
9
>>> digit(3579, 10)
0
"""
return (n%pow(10,k+1))//pow(10,k)
Q4: Middle Number
def middle(a, b, c):
"""Return the number among a, b, and c that is not the smallest or largest.
Assume a, b, and c are all different numbers.
>>> middle(3, 5, 4)
4
>>> middle(30, 5, 4)
5
>>> middle(3, 5, 40)
5
>>> middle(3, 5, 40)
5
>>> middle(30, 5, 40)
30
"""
return max(min(a,b),min(a,c),min(b,c))
返回三个数中的中间值关键是将最大的数分离开,将三个数变成两个数的问题。
Q5: Syllabus Quiz
此处未进行分析。
Q6: Falling Factorial
def falling(n, k):
"""Compute the falling factorial of n to depth k.
>>> falling(6, 3) # 6 * 5 * 4
120
>>> falling(4, 3) # 4 * 3 * 2
24
>>> falling(4, 1) # 4
4
>>> falling(4, 0)
1
"""
"*** YOUR CODE HERE ***"
b=n
c=1
if k ==0:
return 1
else:
for i in range(k) :
c = c*b
b=b-1
return c
分成两种情况来处理。由于是给出了乘数的个数,因此使用循环数已知的for循环。
Q7: Divisible By k
def divisible_by_k(n, k):
"""
>>> a = divisible_by_k(10, 2) # 2, 4, 6, 8, and 10 are divisible by 2
2
4
6
8
10
>>> a
5
>>> b = divisible_by_k(3, 1) # 1, 2, and 3 are divisible by 1
1
2
3
>>> b
3
>>> c = divisible_by_k(6, 7) # There are no integers up to 6 divisible by 7
>>> c
0
"""
"*** YOUR CODE HERE ***"
a=0
for i in range(n):#
if (i+1) % k == 0 :
a = a + 1
print(i+1)
return a
Q8: Sum Digits
def sum_digits(y):#想了很久才想出来的方法,已尽可能简化
"""Sum all the digits of y.
>>> sum_digits(10) # 1 + 0 = 1
1
>>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12
12
>>> sum_digits(1234567890)
45
>>> a = sum_digits(123) # make sure that you are using return rather than print
>>> a
6
"""
"*** YOUR CODE HERE ***"
b = 0
m = 0
while y!= 0:
m = y % pow(10,1)
y = (y-m)//10
b = b+m
return b
将求所有位的数的问题都转化成求个位的数的问题。
Q9: WWPD: What If?
注意return和print的差异。
Q10: Double Eights
def double_eights(n):#思考相邻的两个8意味着什么.如何在while循环中表示两个相邻的值?
"""Return true if n has two eights in a row.
>>> double_eights(8)
False
>>> double_eights(88)
True
>>> double_eights(2882)
True
>>> double_eights(880088)
True
>>> double_eights(12345)
False
>>> double_eights(80808080)
False
"""
"*** YOUR CODE HERE ***"
b = 0
m = 0
while n!= 0:
m = n % pow(10,1)#8
n = (n-m)//10 #28
b = n % pow(10,1)#8
if m==b and m==8:
return True
return False
是在Q8的代码上的修改。核心是比较相邻两个数。