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)
print(val)

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]
print(arr)

3. Python Dictionary Comprehension

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

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
print(dict(Counter("ababacd")))
#Counter({'a': 3, 'b': 2, 'c': 1, 'd': 1})

Using List Comprehension

msg = "ababcd"
dic = [(i, msg.count(i)) for i in set(msg)]
print(dict(dic))
#{'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
print(list(dic))

# 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.

2 Comments

  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 *