對於一個賦值,我們被要求編寫一個函數,它將輸入2個列表作爲輸入,然後返回一個包含'列表1'和'列表2'中所有名稱的列表。合併排序2列表查找通用元素
它被要求使用基於合併排序的算法來完成。到目前爲止,我所得到的結果都會返回正確的列表,但是我正在進行太多比較以獲取此列表。 VoterList是給予我們的指定類,以便我們不使用普通的Python列表。只有VoterName對象(由兩個輸入列表組成)能夠被附加到VoterList。通過的名單都是按字典順序排列的。
歡迎任何關於如何減少比較的建議。謝謝。
from classes import VoterList
def fraud_detect_merge(first_booth_voters, second_booth_voters):
fraud = VoterList()
length_first = len(first_booth_voters)
length_second = len(second_booth_voters)
first_booth_position = 0
second_booth_position = 0
comparisons = 0
while first_booth_position < length_first:
if second_booth_position == length_second:
first_booth_position += 1
second_booth_position = 0
else:
name_comparison = first_booth_voters[first_booth_position]
comparisons += 1
if second_booth_voters[second_booth_position] == name_comparison:
fraud.append(second_booth_voters[second_booth_position])
first_booth_position += 1
second_booth_position = 0
else:
second_booth_position += 1
return fraud, comparisons
非常感謝。這非常有幫助。沒有做到這一點,但它啓發了另一個:) – Mikey
嘿,有沒有什麼機會我可以快速跳進聊天室?謝謝:) – Mikey