Python Tricks for Competitive Programming

Python Tricks for Competitive Programming

1. Sort List of Tuples by Second Value in Reverse Order

val = [('v', 3), ('a', 4), ('b', 2)]
val.sort(key = lambda x: x[1], reverse=True)

Reference: Sort List of Tuples by First/Second value

2. List of Cubes of First 5 Odd Numbers using List Comprehension

arr = [i*3 for i in range(10) if i%2]

3. Python Dictionary Comprehension

dic = [(i, i*2) for i in range(10)]

4. Python Map Example

print(list(map(lambda x: x*2, range(10))))

Reference: Lambda Function

5. Python Filter Example

print(list(filter(lambda x: x%2, range(10))))

6. Python Reduce Example

from functools import reduce
print(reduce(lambda x,y: x+y, range(10)))

7. Permutation

import itertools
itertools.permutations('ABCD', 2)

Reference: Get permutation of a string

8. Selecting Random Number

import random
print(random.choice(range(1, 10)))

Reference: Selecting random number

9. Get the Frequency of Characters in String

Using Collection Counter

from collections import Counter
#Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1})

Using List Comprehension

msg = "ababcd"
dic = [(i, msg.count(i)) for i in set(msg)]
#{'c': 1, 'b': 2, 'd': 1, 'a': 2}

10. Convert Python Dict to List

dic = {'a': 3, 'b': 2, 'c': 1, 'd': 1}

# list of dictionary keys

# list of dictionary values
print([v for k, v in dic.items()])

11. Convert Integer to Binary String

num = 9
binary_num = bin(num).replace("0b", "")  #1001

These Python Tricks for Competitive Programming will help you for solving competitive coding challenges in coding interviews.


  1. Been Looking for an easy way to an Integer into binary. Thank you for the code. It helped! 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *