Skip to main content
 首页 » 编程设计

python之测试没有重复元素的列表

2024年10月25日10lexus

没有一组指令,但我基本上必须为 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 values 表示在列表不为空时执行此操作

pop 方法从列表中取出最后一个元素。但它有副作用,这意味着它会改变初始输入的值:

>>> [1,2,3].pop() 
3 
>>> a = [1,2,3] 
>>> a.pop() 
3 
>>> a 
[1, 2]