[英]Using python to sum n terms of a sequence using only for and while loops
[英]Duplicates in a sequence using ONLY for loops in Python
給定一個序列,我想知道如何在Python中僅使用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
為此, 我們遍歷當前列表,檢查從第二個元素開始是否存在重復項,並查看該特定元素是否存在於列表開頭。
為了使索引從0
開始到當前索引一直到當前索引,我們在列表中使用slice[:]
操作,並使用in
運算符檢查當前元素是否在該子列表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
截取未迭代值的一部分:
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))
由於從性能角度有一些建議,我的解決方案是從可讀性角度來看。 最好使用enumerate
來獲取index
。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.