Python¶
Caveats¶
Please keep in mind that everything in Python is slow. If you estimate that your Python solution is 10 times slower than your C++ solution, you are in the right ballpark.
You can run Python code with either PyPy (using the command pypy3
) or CPython (using the command python3
). PyPy is often (but not always) faster than CPython. In CSES you can select when you submit your code whether you would like to use PyPy or CPython to benchmark your code; PyPy is usually the right choice.
Be careful when handling large inputs. For example, assume your input consists of one million numbers, one per line, and you need to compute their sum. A natural solution along these lines might take something in the ballpark of 4 seconds:
s = 0
for i in range(1000000):
s += int(input())
print(s)
However, you can easily speed it up by a factor of ten if you do something like this:
print(sum(int(x) for x in sys.stdin.read().split()))
In particular, we avoided here calling input()
a million times.
Easy mistakes¶
Please do not confuse operators /
(convert to floating point and divide) and //
(floor division).
Conveniences¶
One convenient feature in Python is that its native integer type supports arbitrarily large numbers. Try it if you have not seen it in action: simply type 123**456
in the Python interpreter and you will get back a 953-digit number. You can easily convert large integers to strings with str
and back to integers with int
. You can try to find creative uses for large integers—integer multiplication is a very powerful tool!