【问题标题】:Find the 1 based position to which two lists are the same找到两个列表相同的基于 1 的位置
【发布时间】:2013-03-17 05:14:30
【问题描述】:

挑战是编写一个函数来比较两个相当小的整数列表(每个列表通常少于 10 个元素)。 一个列表可能是这样的:

self = [0, 0, 1, 2]

要与之比较的列表可能类似于以下示例之一:

other1 = []
other2 = [0, 0, 1]
other3 = [0, 0, 1, 2, 0]
other4 = [0, 1, 1, 2]
other5 = something

如您所见,重复元素很常见,元素的顺序很重要。

预期的结果应该是一个整数,表示self和other相同的时间,从头开始计数。因此,根据其他情况,结果将是:

result1 = 0
result2 = 3
result3 = 4
result4 = 1
result5 = 0

代码应该是最有效的,因为每次用户交互都要使用大约 100 次。

我编写了以下代码,它可以按需要工作,但似乎有点慢:

def match(self, other):
    if self == other:
        return len(self)
    element = -1
    for element in range(min(len(self),  len(other))):
        if self[element] != other[element]:
            element -= 1
            break
    return element +1

第一个 if 语句已经是加快处理速度的增强,但解决方案似乎仍然很慢,而且对变量命名元素和两个返回语句的所有更正看起来也有点笨拙。

有谁比'match'或'compare'更好的函数命名吗?

【问题讨论】:

  • common_prefix_size(list1, list2) 可能是比match 更好的名字

标签: python list


【解决方案1】:
>>> from itertools import takewhile, izip
>>> def F(seq1, seq2):
        return sum(1 for x in takewhile(lambda x: x[0] == x[1], izip(seq1, seq2)))

>>> F([0, 0, 1, 2], [0, 0, 1, 2, 0])
4

【讨论】:

【解决方案2】:

related question 中,我发布了以下可能的解决方案:

def while_equal(seq, other):
    for this, that in zip(seq, other):
        if this != that:
            return
        yield this

def match(seq, other):
    return sum(1 for _ in while_equal(seq, other))

def match_loop(seq, other):
    count = 0
    for this, that in zip(seq, other):
        if this != that:
            return count
        count += 1
    return count

这些版本都比其他给定的解决方案更快(第二个是最快的),而且我认为更具可读性。

【讨论】:

    【解决方案3】:

    编辑: 正如 jamylak 指出的那样,我的解决方案是错误的。我会把它留在这里,这样每个想要回答这个问题的人都会看到整个问题,而不仅仅是前两个案例。

    另一个不需要itertools 的解决方案,虽然它不如jamylak's solution 高效。

    def compareLists(list1, list2):
        return sum(map(lambda (x,y): 1 if x == y else 0, zip(list1, list2)))
    

    【讨论】:

    • 起初我做了类似的事情,但后来我意识到这并没有停止计数。尝试案例 4
    • @jamylak 你完全正确,我没有考虑案例 4。:)
    猜你喜欢
    • 1970-01-01
    • 2014-10-23
    • 1970-01-01
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多