I’m trying to solve a codechef beginner problem – Enormous Input Test. My code
a,b = [ int(i) for i in raw_input().split()]
print [input()%b==0 for i in range(a)].count(True)
gets timed out. Another solution, which uses basic for-loops, seems to be working fine.
I believe that list comprehension is quicker than basic for – loops. Then why is the former slower? Also will using generators in this case reduce the memory used and perform the computation faster, if so how can I do it?
Why do you believe that list comprehension is quicker than basic
forloops? (Hint: they are both implemented using the same underlying instructions.)Your code will be executed in some manner like this:
As you can see, it creates a large list in memory, iterates over it to create a second list, and then iterates over the second list to create a count. The list does not ever need to be created.
Some compilers are capable of optimizing hylomorphisms to remove the intermideate list, but I know of no Python implementation capable of this. So you are stuck optimizing by hand.
Note: Do not use
inputin Python 2.x, unless you know what you are doing. I have changed the code to useint(raw_input())because that is safe, whereasinput()is dangerous.