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.
分类:
语言入门 / CS61A
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)