合并排序2列表查找公共元素

时间:2015-08-19 06:35:27

标签: python list python-3.x merge mergesort

对于作业,我们被要求编写一个作为输入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

2 个答案:

答案 0 :(得分:1)

目前尚不清楚您的输入是什么,是否已经排序?你被列入名单。查看可以在列表上执行的操作,您将找到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

答案 1 :(得分:1)

该任务正好要求找到一个解决方案,并且有一个很大的合并排序提示,所以我不打算为你找到答案:)但也许我可以指出代码中发生了什么:使用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循环。

相关问题