DEV Community

Kaushik Varanasi
Kaushik Varanasi

Posted on

Some must know python modules for competitive programming

Python modules — competitive programming
Taking input:

Generally you have an input in CodeChef like this:

1 2 3 4 5 6 7

To get them as a list of numbers simply

_list = map(int, raw_input().split())

Always use the raw_input() function irrespective of the type of input and then convert it using the map function. map functions are one of the most beautiful in python. Worth knowing.
swapping :

a, b = b, a
Slicing operations:

X[:N] — all elements below index N.
X[N:] — all elements above index N.
X[a:b] — all elements between a, b.
And remember python lists are circular
X[-k] gives k’th element from the last. Quite useful to use in slicing also
X[-k:] — gives last k elements.
X[:-k] — gives first n-k elements where n is the length of the list.
There are many more: Neat Features in Python: Slicing and Sliding (Stepping) and Slicing, Dicing and Splicing
Enter fullscreen mode Exit fullscreen mode

While iterating always use xrange() and never range().
This is a common mistake most beginners do. range() gives a list which is a kind of overkill. xrange() is a generator, produces elements one by one and only once. Though if you are using Python3 then it is safe to use range.
sort() function:
Collections module:

Very often you need to remove duplicates. While in languages like java you have to use HashMap and all that shit, in python it’s simply:

_list = list(set(_list)).

Difference between extend() and append() in lists.
merge a=[1, 2, 3] and b=[4, 5, 6] should be
a.extend(b)
which gives

[1, 2, 3, 4, 5, 6]

a.append(b)
gives

[1, 2, 3, [4, 5, 6]]
String concatenations:

strings = ['I', 'am', 'the', 'laziest', 'person', 'in', 'the', 'world' ]
To concatenate the above strings we would be tempted to do:

It gives the right answer but it’s the worst way to do it and has a huge time overhead. The correct way is to use join() function.

Stop using reduce functions in python if you are. They are not well supported and will be deprecated soon. The fate of reduce() in Python 3000 from the inventor of python himself. Start using lambda extensively. See this post Python Lambda — why? — Stack Overflow.

And list goes on and on.
check out this book Writing Idiomatic Python Book
I am sure you can get a pdf somewhere.

Finally, practice !!. HackerRank is best for beginners and especially if you are a python lover, you’ll find it really comfortable.

The above snippet is an answer I wrote on Quora and received a bit of appreciation. I hope it helps here too!

Discussion (0)