Christopher Matthews
Christopher Matthews

Reputation: 25

Array Checksum Algorithm - Python 3

I have been working on problem 17 at Code Abbey. The task is to find the checksum of an array.

I would appreciate an explanation as to why the answer is correct and why my solution is not working.

This is the problem:

You will be given the array for which checksum should be calculated. Perform calculation as follows: for each element of the array (starting from beginning) add this element to result variable and multiply this sum by 113 - this new value taken by modulo 10000007 should become the next value of result, and so on.

Example:

input data:
6
3 1 4 1 5 9

answer:
8921379

All input values are between 0 and 1,000,000,000 - be sure to take care of possible overflow in progress of calculations.

This is my attempt:

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))

Upvotes: 0

Views: 1681

Answers (2)

SilentK
SilentK

Reputation: 652

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]))

This prints out 8921379.

Upvotes: 0

Veedrac
Veedrac

Reputation: 60167

If you add another object to the end of the array you get the right answer:

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

so as Peter de Rivaz says it's because you're missing the last element. Take Kevin's answer and just loop over the items in a:

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

Upvotes: 1

Related Questions