29、请向虚拟助手询问‘用一个单一条件重写此语句’。语句为:x是一个正的一位数。
可以向虚拟助手表述为“Rewrite this statement with a single conditional: x is a positive single-digit number.”,对应的单一条件语句可以是:
if 0 < x and x < 10:
print("x is a positive single-digit number")
或者更简洁的:
if 0 < x < 10:
print("x is a positive single-digit number")
30、查看虚拟助手能否简化以下不必要的复杂代码:if 0 < x: if x < 10: print(‘x is a positive single - digit number.’)
可以使用逻辑运算符 and 来简化嵌套条件语句,简化后的代码为:
if 0 < x and x < 10:
print('x is a positive single-digit number.')
此外,Python 还提供了更简洁的写法:
if 0 < x < 10:
print('x is a positive single-digit number.')
31、下面的递归函数有一个错误,请指出哪里出错了以及如何修复,并对修复后的代码进行测试。函数代码如下:def countdown_by_two(n): if n == 0: print(‘Blastoff!’) else: print(n) countdown_by_two(n-2) countdown_by_two(6)
错误分析
这段递归函数对于输入为偶数时可以正常工作,但是当输入为奇数时会出现问题。因为当输入为奇数时,不断减2最终不会得到0,而是得到一个负数,这样会导致无限递归,最终引发 RecursionError 。
修复方案
我们需要修改终止条件,使得当 n 小于等于0时都能终止递归。修改后的代码如下:
def countdown_by_two(n):
if n <= 0:
print('Blastoff!')
else:
print(n)
countdown_by_two(n - 2)
countdown_by_two(6)
countdown_by_two(7)
测试结果说明
- 当调用
countdown_by_two(6)时,输出为6 4 2 Blastoff!。代码会先打印出6,然后递归调用自身并传入n - 2即4,接着依次打印4和2,当n减到0时,打印Blastoff!。 - 当调用
countdown_by_two(7)时,输出为7 5 3 1 Blastoff!。代码会先打印出7,然后递归调用自身并传入n - 2即5,接着依次打印5、3、1,当n减到 -1 时,由于n <= 0条件满足,打印Blastoff!,避免了无限递归。
32、使用整除和取模运算符计算自1970年1月1日以来的天数以及当前一天中的小时、分钟和秒数。已知当前时间戳为1709908595.7334914 。
以下是解决该问题的Python代码:
from time import time
now = 1709908595.7334914
# 计算总秒数
total_seconds = int(now)
# 计算天数
days = total_seconds // (24 * 60 * 60)
# 计算剩余秒数
remaining_seconds = total_seconds % (24 * 60 * 60)
# 计算小时数
hours = remaining_seconds // (60 * 60)
# 计算剩余秒数
remaining_seconds %= (60 * 60)
# 计算分钟数
minutes = remaining_seconds // 60
# 计算秒数
seconds = remaining_seconds % 60
print(f'自1970年1月1日以来的天数: {days

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



