在 Python 中仅使用 for 循环重复序列

Duplicates in a sequence using ONLY for loops in Python

给定一个序列,我想知道如何在 Python 中使用 ONLY for 循环(没有导入的模块、排序函数等)来查找重复项。到目前为止,这是我的以下代码,其中涉及嵌套 for 循环:

def has_duplicates(list):
    x = 0
    ans = False
    for i in range(len(list)):
        index = i
        for object in list:
            x = object
        if list[i] == x:
            ans = True
            break
    return ans

我真的不知道要为内部循环编写什么代码...是否需要嵌套循环来查找序列的重复项?

以下输出示例:

list = [10, 11, 12, 13, 14, 15]
print(ans)
False
list = "Hello"
print(ans)
True

获取未迭代值的切片:

def has_duplicates(values):
    for index, value in enumerate(values, start=1):
        for other_value in values[index:]:
            if value == other_value:
                return True
    return False

如果可以使用集合:

def has_duplicates(values):
    return len(values) > len(set(values))

为此,我们遍历当前列表,检查从第二个元素开始的重复项,并查看该特定元素是否存在于列表开头的任何位置。

要获取从索引 0 到当前索引的子列表,我们在列表中使用 slice[:] 操作并检查当前元素是否存在于该子列表中,我们使用in 运算符。

您可以执行以下操作:

In [1]: def has_duplicates(my_list):
   ...:     for index in range(len(my_list)): 
   ...:         if index!=0: # check only from 2nd element onwards
   ...:             item = my_list[index] # get the current item
   ...:             if item in my_list[:index]: # check if current item is in the beginning of the list uptill the current element
   ...:                 return True # duplicate exist
   ...:     return False # duplicate does not exist
   ...:

In [2]: has_duplicates([1,2,3,4])
Out[2]: False

In [3]: has_duplicates([1,2,3,4,4])
Out[3]: True

In [4]: has_duplicates([1,1,2,3,4,4])
Out[4]: True

您可以对每个元素进行更有效的前瞻比较;这通过仅将每个元素与其后面的元素进行比较来消除整个列​​表中的冗余比较。我不是 Python 程序员,所以我只是猜测这会起作用;它可能也是这个问题最不惯用的解决方案(意思是 Python 可能有更漂亮的方法来处理这个问题,但它应该工作得很好)。

def has_duplicates(list):
    for i in range(len(list)):
        for j in range(i+1, len(list)):
            if list[i] == list[j]:
                return True
    return False

作为,有一些从性能角度的建议,我的解决方案是从可读性的角度。最好用enumerateindex.

def has_duplicates(list):

    for index,value  in enumerate(list):
        for index2,value2  in enumerate(list):
            if value==value2 and index!=index2:
                return True


    return False

print has_duplicates("Hello")
print has_duplicates([10, 11, 12, 13, 14, 15])

输出:

True
False