# Python Tricks for Competitive Coding

Python is one of the preferred languages among coders for most of the competitive programming challenges. Most of the problems are easily computed in a reasonable time frame using python.

For some of the complex problem, writing fast-enough python code is often a challenge. Below are some of the pythonic code constructs that help to improve the performance of your code in competitive coding −

1. Strings concatenation: Do not use the below construct.

str1 = ""
some_list = ["Welcome ", "To ", "Tutorialspoint "]
for x in some_list:
str1 += x
print(str1)

Above method gives huge time overhead.Instead, try to use this (join method) −

str1 = ""
some_list = ["Welcome ", "To ", "Tutorialspoint "]
print(str1.join(some_list))

2. The Map function

Generally, you have an input in competitive coding, something like −

1234567

To get them as a list of numbers simply

list(map (int, input().split()))

Always use the input() function irrespective of the type of input and then convert it using the map function.

>>> list(map(int, input("enter numbers:").split()))
enter numbers:1 2 3 4 5 6 7
[1, 2, 3, 4, 5, 6, 7]
>>>

The map function is one of the beautiful in-built function of python, which comes handy many times. Worth knowing.

3. Collections module

In case we want to remove duplicates from a list. While in other languages like Java you may have to use HashMap or any other freaky way, however, in pytho it's simply

>>> print(list(set([1,2,3,4,3,4,5,6])))
[1, 2, 3, 4, 5, 6]

Also, be careful to use extend() and append() in lists, while merging two or more lists.

>>> a = [1, 2, 3,4] # list 1
>>> b = [5, 6, 7] # list 2
>>> a.extend(b)#gives one list
>>> a
[1, 2, 3, 4, 5, 6, 7]
>>> a.append(b) # gives list of list
>>> a
[1, 2, 3, 4, [5, 6, 7]]

4. Language constructs

It's better to write your code within functions, although the procedural code is supported in Python.

def main():
for i in range(2**3):
print(x)
main()

is much better than

for x in range(2**3):
print(x)

It is faster to store local variables than globals because of the underlying Cpython implementation.

5. Use the standard library:

It’s better to use built-in functions and standard library package as much as possible. There, instead of −

newlist = []
for x in somelist:
newlist.append(myfunc(x))

Use this −

newlist = map(myfunc, somelist)

Likewise, try to use the itertools(standard library), as they are much faster for a common task. For example, you can have something like permutation for a loop with a few lines of code.

>>> import itertools
>>> iter = itertools.permutations(["a","b","c"])
>>> list(iter)
[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')]

6. Generators

Generators are excellent constructs to reduce both, the memory footprint and the average time complexity of the code you’ve written.

def fib():
a, b = 0, 1
while 1:
yield a
a, b = b, a+b