数组校验和算法 - Python 3

0 投票
2 回答
1589 浏览
提问于 2025-04-21 04:16

我在Code Abbey上做第17题,任务是计算一个数组的校验和。

我希望能得到一个解释,告诉我为什么答案是正确的,以及为什么我的解法不行。

这是题目:

你会得到一个数组,需要计算它的校验和。计算方法是:从数组的第一个元素开始,把这个元素加到一个叫result的变量上,然后把这个和乘以113,接着用10000007去取模,得到的新值就是result的下一个值,然后继续这个过程。

举个例子:

input data:
6
3 1 4 1 5 9

answer:
8921379

所有输入值都在01,000,000,000之间,所以在计算过程中要注意可能出现的溢出问题。

这是我的尝试:

a = [int(x) for x in input().split()]

def get_checksum(a):
    seed = 113
    limit = 10000007
    result = 0

    for i in range(len(a) - 1):
        result += a[i]
        result *= seed
        result %= limit

    return result

print(get_checksum(a))

2 个回答

0
def get_checksum(a):
    seed = 113
    limit = 10000007
    result = 0

    for i in range(len(a)):
        result += a[i]
        result *= seed
        result %= limit

    return result

    print(get_checksum([3, 1, 4, 1, 5 , 9]))

这段代码会输出 8921379

1

如果你在数组的末尾再加一个对象,你就能得到正确的结果:

a = [3, 1, 4, 1, 5, 9, "X"]

def get_checksum(a):
    seed = 113
    limit = 10000007
    result = 0

    for i in range(len(a) - 1):
        result += a[i]
        result *= seed
        result %= limit

    return result

print(get_checksum(a))
#>>> 8921379

所以正如Peter de Rivaz所说,你缺少了最后一个元素。你可以参考Kevin的回答,简单地遍历一下中的所有项目:

a = [3, 1, 4, 1, 5, 9]

def get_checksum(a):
    seed = 113
    limit = 10000007
    result = 0

    for item in a:
        result += item
        result *= seed
        result %= limit

    return result

print(get_checksum(a))
#>>> 8921379

撰写回答