Search code examples
pythonarraysalgorithmchecksum

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

Solution

  • 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