Python modules — competitive programming
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.
a, b = b, a
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
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.
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
[1, 2, 3, 4, 5, 6]
[1, 2, 3, [4, 5, 6]]
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!