Reputation: 25
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.
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 by113
- this new value taken by modulo10000007
should become the next value ofresult
, and so on.Example:
input data: 6 3 1 4 1 5 9 answer: 8921379
All input values are between
0
and1,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
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
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