簡體   English   中英

合並排序2列表以查找常見元素

[英]Merge Sort 2 Lists Finding Common Elements

對於一項分配,我們被要求編寫一個函數,該函數接受2個列表作為輸入,然后返回一個包含“列表1”和“列表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

您輸入的內容尚不清楚,是否已經排序? 您會收到清單。 查看可以對列表執行的操作,您將找到pop()操作。 這將從列表中刪除一項,並提供其價值。 由於列表都是按順序排列的,因此可以使用以下方法:

def fraud_detect_merge(first_booth_voters, second_booth_voters):
    fraud = VoterList()
    comparisons = 0

    first_booth_voters.sort()     # if not already sorted
    second_booth_voters.sort()    # if not already sorted

    first = first_booth_voters[0]
    second = second_booth_voters[0]

    while first_booth_voters and second_booth_voters:
        comparisons += 1

        if first == second:
            fraud.append(first)
            first = first_booth_voters.pop(0)
            second = second_booth_voters.pop(0)
        elif first < second:
            first = first_booth_voters.pop(0)
        else:
            second = second_booth_voters.pop(0)

    return fraud, comparisons

分配恰好要求找到一個解決方案,並且有很大的合並排序提示,因此我不會為您提供答案:)但是也許我可以指出您的代碼中正在發生的事情:使用while循環在最壞的情況下,您基本上完成了兩個長度為length_firstlength_second嵌套循環:

for name_comparison in first_booth_voters:
  for second_name in second_booth_voters:
    comparisons += 1
    if second_name == name_comparison:
      fraud.append(second_name)
      break

在最壞的情況下,將導致length_first x length_second比較。 鑒於輸入列表已排序,這當然不是最佳選擇。 您需要利用排序的優勢。 而且,如果輸入列表未排序,則應考慮使用更具可讀性的嵌套for循環替換難以閱讀/調試/理解while循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM