我来自Java背景,我正在尝试用2018年代码挑战来教自己Python(这是第1天第2部分) . 我知道集合提供了更快的搜索速度,并且不允许重复,这使得它们成为最合适的解决方案 . 但是,我的理解是列表仍然可以检测重复(虽然它会更慢) . 有人可以解释为什么列表在这种情况下无法找到正确的答案吗?
使用set:此代码会打印第一个重复的freq值:
# the text file contains many positive and negative integers separated by /n
data = [int(x) for x in open("filepath.txt").readlines()]
freq = 0
seen = {0}
flag = True
while flag:
for num in data:
freq += num
if freq in seen:
print(freq)
flag = False
break
seen.add(freq)
使用列表:此代码不会打印任何内容并无限循环:
# the text file contains many positive and negative integers separated by /n
data = [int(x) for x in open("filepath.txt").readlines()]
freq = 0
seen = [0]
flag = True
while flag:
for num in data:
freq += num
if freq in seen:
print(freq)
flag = False
break
seen.append(freq)
在此先感谢您的帮助 . 我花了几个小时试图弄清楚没有运气,尽管我确信这很简单 .