没有一组指令,但我基本上必须为 def hasNoDuplicate
编写代码,并且当列表没有重复项时它会返回 True
。这就是我写的,我是编程新手,所以所有这些都令人难以承受。我不知道在 if
语句中到底要放什么。任何建议都会有很大帮助!
def hasNoDuplicates(values):
foundCounterExampleYet = False
for value in values:
if():
foundCounterExampleYet = True
return not(foundCounterExampleYet)
最佳答案
def hasNoDuplicates(values):
foundCounterExampleYet = False
value = None
while values:
value = values.pop()
if value in values:
foundCounterExampleYet = True
break
return not(foundCounterExampleYet)
现在你得到:
>>> hasNoDuplicates([1,2,3])
True
>>> hasNoDuplicates([1,2,3,4,6,7,8,9,4])
False
>>>
这段代码的作用是,它获取输入列表,然后逐个取出列表中的最后一个元素,并检查该项目是否存在于列表中。如果存在,则检测到重复,并更改 foundCounterExampleYet
的值,从而跳出循环。进行此检查直到列表变空。 while value
表示在列表不为空时执行此操作
pop
方法从列表中取出最后一个元素。但它有副作用,这意味着它改变了初始输入的值:
>>> [1,2,3].pop()
3
>>> a = [1,2,3]
>>> a.pop()
3
>>> a
[1, 2]
关于python - 测试没有重复元素的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27366670/