【问题标题】:Two arrays sorted to see if they have the same value, but it only picks up that there are 2/3 values that are the same in the arrays对两个数组进行排序以查看它们是否具有相同的值,但它只会发现数组中有 2/3 的值相同
【发布时间】:2019-10-06 17:39:14
【问题描述】:

我不知道为什么只有三分之二的值在我的代码中显示它们是相同的,我是否遗漏了什么?

def occurInBoth(B,A):
    occured = 0
    for i in range(len(A)):
        if A[i] == B[i]: 
            occured += 1

    return occured



A = [5,12,31,7,25]
sorted(A)
A.sort()
print(A)
B = [4,12,7,31,42,8]
sorted(B)
B.sort()
print(B)
occured = occurInBoth(B,A)
print(occured)

你能告诉我吗?

【问题讨论】:

  • 两者已排序的事实意味着这两个值将出现在同一个索引处。
  • sorted 的调用没有做任何事情,因为它们没有修改列表,并且您没有分配返回值。

标签: python arrays algorithm


【解决方案1】:

您的算法存在逻辑错误。如果对两个列表进行了排序,那 not 是否意味着这些项目将出现在相同的索引处。

确实,以您的示例中的排序列表为例:

A = [5, 7, 12, 25, 31]
B = [4, 7,  8, 12, 31, 42]

如您所见,12 出现在两个列表中,但不在同一个索引处。

但是,您可以利用列表已排序的事实:

def occurInBoth(a, b):
    occured = i = j = 0
    while i < len(a) and j < len(b):
        if a[i] < b[j]:
            i += 1
        elif a[i] > b[j]:
            j += 1
        else:
            occurred += 1
            i += 1
            j += 1

【讨论】:

  • 哦,我明白了,因为它不在同一个索引号中,编译的代码认为它们不匹配:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-10
  • 2017-07-02
  • 2014-02-03
  • 2020-01-16
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
相关资源
最近更新 更多