cs61a pingpong
时间: 2023-11-18 08:05:36 浏览: 33
"pingpong" 是 CS61A 课程中的一个编程练习,要求学生编写一个函数,接收一个整数 n 和一个布尔值 direction,输出从 1 到 n 的数字,按照“乒-乓”游戏的规则,即当 direction 为 True 时,将所有 3 的倍数和 5 的倍数替换为 "ping" 和 "pong",当 direction 为 False 时,将所有 3 的倍数和 5 的倍数替换为 "pong" 和 "ping"。例如,当 n=8,direction=True 时,输出为 [1, 2, "ping", 4, "pong", "ping", 7, 8]。
以下是一个实现该函数的示例代码:
```python
def pingpong(n, direction=True):
"""
Return the sequence of integers from 1 to n with ping-pong rules:
- If a number is divisible by 3 or has a 3 in it, replace it with "ping".
- If a number is divisible by 5 or has a 5 in it, replace it with "pong".
- If a number satisfies both rules, replace it with "ping-pong".
"""
def helper(i, p, result):
if i == n:
return result + [p]
elif i % 3 == 0 or '3' in str(i):
return helper(i+1, 'ping' if p == 'pong' else 'pong', result+[p])
elif i % 5 == 0 or '5' in str(i):
return helper(i+1, p, result+['ping-pong' if p == 'ping' else i])
else:
return helper(i+1, p, result+[i])
return helper(1, 'ping', []) if direction else helper(1, 'pong', [])
```
这个函数使用了递归来遍历整数序列,并根据规则替换数字。值得注意的是,helper 函数的第二个参数 p 表示当前的“乒-乓”状态,方便在规则中切换。