【发布时间】:2015-08-19 06:35:27
【问题描述】:
对于一项作业,我们被要求编写一个函数,该函数将 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
【问题讨论】:
标签: python list python-3.x merge mergesort