Search code examples
pythonnumberscalculationalgebraic-data-types

Why can't python sum properly?


I have this code snippet:

import math
number_of_lists, M = list(map(int, input().split(" ")))
print(sum([math.pow(max(list(map(int, input().split(" ")))), 2) for i in range(number_of_lists)]) % M)

Im dealing with really LARGE numbers. When I calculate the final result it doesn't yeild the same as the google calculator. Does anyone know why is that. When I replace the final value of the sum with that of the google calculator it returns correct answer. I tried changing it to float but it didn't work, I looked around for some kind of bigger datatype, but it seems as int should be able to handle the numbers.

Here is a sample input:

7 671
7 5678403 6770488 5713245 6503478 7774748 5900452 531896
7 7728332 501199 9141815 7341382 7238970 8282671 3037527
7 7763981 7041667 3521352 9616160 7322888 5685405 6017382
7 7278231 1143649 6460915 8159948 2436146 1238439 9869216
7 1422820 9424407 4982886 7101222 8711246 696130 6121051
7 6485993 6596581 9169298 4214325 7097779 827465 4072058
7 6853100 9110135 9625936 7133432 8668153 5663640 6749591

it should return 670, but it return 53. Sorry if the code is a bit cramped up I'm just trying to solve it with the least amount of lines. Here is a link to the exercise: https://www.hackerrank.com/challenges/maximize-it/problem?isFullScreen=true


Solution

  • Try this code to see if it can help - it simplify the reading and processing and make it more readable (for maintain and debug).

    Sometimes, we want to impress people and make one-liner or compact code, thus sacrifice the readability. I don't recommend that.

    import itertools as it
    
    K, M = map(int, input(), split())   
    
    # reading the K lines and appending lists to LL
    LL = []
    
    for i in range(K):
        ll = list(map(int, input().strip().split()))
        LL.append(ll[1:])    # skip the first num
    
    MAX = -1
    
    # looping thr Cartesian Product of LL lists and get the max now
    for i in it.product(*LL):
        MAX = max(sum(map(lambda x: x**2, i)) % M, MAX)
    
    print(MAX)