Python in Competitive Programming

Python Methods and Functions

Let me demonstrate with a simple example, take a look at the following code snippets:

alphabets = [ 'a' , 'b' , ' c' ]

for item in alphabets:

  len (item) 

alphabets = [ ' a' , 'b' , 'c' ]

fn = len

for item in alphabets:

  fn (item)

You might think that I have assigned an alias to len function and that may not matter. 
So I wrote a performance test function like this.

import datetime

alphabets = [ str (x) for x in range ( 10000000 )]

a = datetime.datetime.now () # save start time

for item in alphabets:

  len (item)

b = datetime.datetime.now () # last store

print (b - a) .total_seconds () # Results

a = datetime.datetime.now ()

fn = len   # function is stored locally

for item in alphabets:

fn (item)

b = datetime.datetime.now ()

print (b - a) .total_seconds ()

I encourage you to try this on your systems. 
Here is my conclusion about running the performance.py script.

Almost half!

Ok, now let's try to analyze why this happened. Cause? Finding a function is an expensive operation. 
In the second snippet, I have stored the function directly in the scope of the function, so it doesn't matter how many times I call it, every time the runtime knows exactly where it should look for the results.


If you've been to codeforces, you already know that a lot of programming problems involve backtracking. So, today I am going to tell you about a library for generating all permutations and combinations using the built-in library package, which is extremely fast. Itertools. If you want to solve algorithmic problems with Python, then itertools — this is a library you should definitely learn. 
To generate all permutations —

from itertools import permutations

perm = permutations ([ 1 , 2 , 3 ], 2 )

for i in list (perm):

print i

 
# The answer is & gt; (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)

Combination () functions behave similarly. I encourage readers to try it out for themselves.

Python is a slow language only if your code is not leveraging the power of it successfully. Do not feel like you are at a disadvantage if you're a python coder, it's actually very neat and very quick!





Get Solution for free from DataCamp guru