【发布时间】:2016-05-10 10:28:59
【问题描述】:
任务是检查两个列表中对应项目的最后 3 位数字是否相同。如果项目的长度小于 3,则检查它们是否是相同的数字。
如果两个列表的长度不同,则应返回 false,如果两个列表的长度均为 0,则应返回 true。
def corresponding_elements_have_same_end(list1, list2):
if len(list1) == len(list2):
for i in range(0, len(list1)):
num1 = str(list1[i])
num2 = str(list2[i])
if len(num1) <= 3 and len(num2) <= 3:
return num1 == num2
else:
return num1[-3:] == num2[-3:]
else:
return False
如果我运行它:
print("1.", corresponding_elements_have_same_end([3452, 43600, 10], [3111452, 600, 10]))
print("2.", corresponding_elements_have_same_end([452, 43600], [52, 600]))
print("3.", corresponding_elements_have_same_end([32, 43032], [32, 32]))
print("4.", corresponding_elements_have_same_end([32, 43132, 300], [32, 56132, 3300]))
打印出来
- 是的
- 错误
- 是的
- 是的
何时打印:
- 是的
- 错误
- 错误
- 是的
【问题讨论】:
-
你应该考虑使用 mod, %,而不是 str。 num# = list#[i] % 1000.