Why is this code so slow on CodeChef but performs much faster on my computer?

For the Enormous Input Test problem, I submitted the following Python 3.4 code:

import sys

numOfLines, numberToDivideBy = input().split()

numsDivisible = 0

for i in range(int(numOfLines)):
    line = sys.stdin.readline()
    if int(line) % int(numberToDivideBy) == 0:
        numsDivisible += 1

print(str(numsDivisible),end='')

This works totally fine on my machine. Even with nearly 2 million input integers, all of which are around 10^9 in size, divided by an integer 10^7 in size, it can complete the entire thing in around 3 or 4 seconds. Yet when I submit this, CodeChef claims it takes 24 seconds for their tests.

Here’s another rendition of my code using map and generator expression and stuff:

import sys

numOfLines, numberToDivideBy = map(int,input().split())

numsDivisible = 0

everything = sys.stdin.read().split()

numOfLines = numOfLines if numOfLines < len(everything) else len(everything)

everything = (int(x) for x in everything)

for i in range(numOfLines):
    if next(everything) % numberToDivideBy == 0:
        numsDivisible += 1

print(str(numsDivisible),end='')

Same problem.

1 Like