I don't understand why "Total = 0" in python makes the code faster

I am trying to work through some of the practice problems and I am still very new to this. I figured out the problem but failed because of timing. I looked up the answer and was missing a line of code that read “Total = 0” when I put that line of code in it sped up the code by .02sec. Can someone explain to me how this is?

My code:
t = int(input())
inputs = [input().split() for y in range(t)]
for a, b in inputs:
print(eval(a) % eval(b))

.05 sec to run the example in put

Correct code:
t = int(input())
inputs = [input().split() for y in range(t)]
total = 0
for a, b in inputs:
print(eval(a) % eval(b))

.03 sec to run example input

It should make no difference. The timing can vary a little though, even running exactly the same code twice. You certainly won’t fail on timing when using a modulo operator; I doubt you would hit the timing limit even if you found the remainder by repeated subtraction.

That code is anyway not a good example for a beginner of how to solve the problem. Hopefully that default solution for FLOW002 can be updated @admin

This is a more straightforward solution:

T = int(input())
for x in range(T):
    A,B = map(int, input().split())
    print(A % B)
1 Like

Thanks. We have replaced the template with your code. Please feel free to make suggestions in any of the problems’ templates.

1 Like

Thank you! I do have another question. I don’t understand why you used int, instead of int(). I ran both and I get an error for int() but I don’t quite understand why.

map takes two parameters, and the first one is a function (which is applied to each member of the second parameter). So what we want there is the function int rather than the function result int() which will just evaluate to zero.

map(int,input().split())
could be thought of as:
(int(s) for s in input().split())

Coding here can make you a little lazy on testing input against expectations, and this is a case in point; this code is trusting completely that there will indeed be two parameters on the line being split here, allowing the assignment to A,B from the two-value list.

2 Likes

I suggest you also include the guidance text preamble (as previously) in the template solution, that is:

# We have populated the solutions for the 10 easiest problems for your support.
# Click on the SUBMIT button to make a submission to this problem.

T = int(input())
for x in range(T):
    A,B = map(int, input().split())
    print(A % B)

@admin

1 Like