CS61A_lab03
题目描述:

代码:
1 def num_eights(x): 2 """Returns the number of times 8 appears as a digit of x. 3 4 >>> num_eights(3) 5 0 6 >>> num_eights(8) 7 1 8 >>> num_eights(88888888) 9 8 10 >>> num_eights(2638) 11 1 12 >>> num_eights(86380) 13 2 14 >>> num_eights(12345) 15 0 16 >>> from construct_check import check 17 >>> # ban all assignment statements 18 >>> check(HW_SOURCE_FILE, 'num_eights', 19 ... ['Assign', 'AugAssign']) 20 True 21 """ 22 "*** YOUR CODE HERE ***" 23 if x==0: 24 return 0 25 return num_eights(x//10)+(x%10==8) 26 27 28 29 def pingpong(n): 30 """Return the nth element of the ping-pong sequence. 31 32 >>> pingpong(8) 33 8 34 >>> pingpong(10) 35 6 36 >>> pingpong(15) 37 1 38 >>> pingpong(21) 39 -1 40 >>> pingpong(22) 41 -2 42 >>> pingpong(30) 43 -2 44 >>> pingpong(68) 45 0 46 >>> pingpong(69) 47 -1 48 >>> pingpong(80) 49 0 50 >>> pingpong(81) 51 1 52 >>> pingpong(82) 53 0 54 >>> pingpong(100) 55 -6 56 >>> from construct_check import check 57 >>> # ban assignment statements 58 >>> check(HW_SOURCE_FILE, 'pingpong', ['Assign', 'AugAssign']) 59 True 60 """ 61 "*** YOUR CODE HERE ***" 62 #special case : 63 #1. n%8==0 2. num_eights(n)>0 64 #我的问题在于如何确定是正在递增还是正在递减呢 65 #肯定是返回前一个数的函数再加上1或者减去1 66 #如果是正在递增,则返回上一个数的函数+1,如果是递减,则返回上一个数的函数-1 67 def helper(i,value,direction): 68 if i==n: 69 return value 70 if num_eights(i)!=0 or i%8==0: 71 return helper(i+1,value-direction,direction*-1) 72 #用来改变方向 73 else : 74 return helper(i+1,value+direction,direction) 75 return helper(1,1,1) 76 #从起点开始往后递归,而不是从终点往前递归 77 #启示:如果只有一个参数不够反应情况,那么就可以再重新定义一个函数
启示:
- 递归不一定是要从后往前递归,也有可能是从前往后递归
- If you need to keep track of more than one value across recursive calls, consider writing a helper function.

浙公网安备 33010602011771号