I would like to know how to improve the execution speed of the code below.

The context : n is an integer read from the stdin, and represents the number of cases. Each case is represented by a sequence of characters (can only be uppercase alphabet letters), that are read from stdin. For each case, if the sequence doesn't contain the sub-string "CD", we add 1 to the variable wins.

Finally, we print out wins : the number of strings not containing the string "CD".

n = int(raw_input()) #number of cases
wins = 0
for i in range(n):
    if "CD" not in raw_input(): #count number of strings that doesn't contain "CD"
        wins += 1
print wins

Note: Official Python performance tips suggest using map or list comprehension instead of for loop to speed up, but I couldn't implement those without the for loop.

What other ways to speed the execution speed, knowing that every thing read from the stdin is necessary, and that the typing speed (I use python filename.py <input.txt method) isn't an issue (I'm looking for a way pertaining to the code structure, to speed the execution itself) ?

  • \$\begingroup\$ Why delete your old - hour ago - question? You can always add more information by editing your question. Would you care to add the information about you doing something like python file.py < something or other that you deleted from the comments on the last question? \$\endgroup\$
    – Peilonrayz
    Commented Sep 29, 2017 at 20:19
  • \$\begingroup\$ @Peilonrayz Thank you. I edited the question to include that. \$\endgroup\$ Commented Sep 29, 2017 at 20:25

2 Answers 2


If you used better variable names, you wouldn't need your first comment. The second one, though, is pure noise as it just repeat the code without adding anything.

To save on memory (and thus a bit on speed as you won't need to allocate the array) you should use xrange rather than range.

You don't use the variable i so better call it _ as it is a convention in Python for unused variables.

Lastly, you can use the sum built-in and a generator expression to perform the looping in C rather than in Python:

cases_count = int(raw_input())
wins = sum('CD' not in raw_input() for _ in xrange(cases_count))
print wins

Try xrange instead of range.

If typing speed and such are not an issue, then stdin is a file. Treat it as a file- try reading the entire contents, or using for line in sys.stdin, or using .readlines().


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.