DEV Community

Omkar Bhagat
Omkar Bhagat

Posted on

Python: last minute notes for your coding interviews

If you are someone who opts for the Python language for your coding (data structures and algorithms) interviews, then you may want to bookmark this post for your last minute revision.

1. Convert dictionary key-values to a list of tuples

seen = {'i': 2, 'love': 2, 'leetcode': 1, 'coding': 1}

seen.items()
# [('i', 2), ('love', 2), ('coding', 1), ('leetcode', 1)]
Enter fullscreen mode Exit fullscreen mode

2. Populating a dictioonary with +1/-1

Quickly increment or decrement a value of a key in a dictionary:

seen[c] = 1 + seen.get(c,0)
seen[c] = seen.get(c,0) - 1
Enter fullscreen mode Exit fullscreen mode

3. Sort based on key and reverse

# sorting interval at index i 
# by 1st value as key in that interval
# [ [1,2], [3,4] ]
# and then reversing the result
# [ [3,4], [1,2] ]

items.sort(key=lambda x: x[1], reverse=True)
Enter fullscreen mode Exit fullscreen mode

4. Check if list type

if isinstance(x, list)

# OR

if type(x) is list
Enter fullscreen mode Exit fullscreen mode

5. ASCII values

ord('A') = 65

ord('Z') = 90

ord('a') = 97

ord('z') = 122

chr(65) = 'A'
Enter fullscreen mode Exit fullscreen mode

6. Limit float to 2 decimal places

round(x, 2)
Enter fullscreen mode Exit fullscreen mode

7. Using a double ended queue

from collections import deque

>>> word = 'hit'

>>> q = deque([word])
>>> q
deque(['hit'])

>>> q = deque(word)
>>> q
deque(['h', 'i', 't'])

# functions like these exist:
# q.appendleft
# q.popleft
# q.append
# q.pop
Enter fullscreen mode Exit fullscreen mode

8. Creating adjacency list with defaultdict

from collections import defaultdict

neighbours = defaultdict(list)

# creates a structure like this:
# neighbours = {
#     key1: [item1, item2],
#     key2: [item1, item2, item3],
# }

# can be populated as follows:
for key, val in somelist:
    neighbours[key].append(val)

Enter fullscreen mode Exit fullscreen mode

9. Intersection of two sets

>>> a = { 1, 2, 3 }
>>> b = { 3, 4, 5 }
>>> a.intersection(b)
{3}
>>> list(a.intersection(b))
[3]
Enter fullscreen mode Exit fullscreen mode

10. Combinations vs Permutations

a = "ABC"

>>> list(itertools.permutations(a))
[('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')]

>>> list(itertools.combinations(a, 3))
[('A', 'B', 'C')]

>>> list(itertools.combinations(a, 2))
[('A', 'B'), ('A', 'C'), ('B', 'C')]

>>> list(itertools.permutations(a, 2))
[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
Enter fullscreen mode Exit fullscreen mode

11. Reading input line by line

if __name__ == '__main__':
    n = int(input().strip())

    words = []

    for _ in range(n):
        words_item = input()
        words.append(words_item)

    # call some function after reading..
    noPrefix(words)
Enter fullscreen mode Exit fullscreen mode

12. Writing test cases

class Solution:

    def twoSum(self, nums, target):

        seen = {}

        for i, num in enumerate(nums):
            num2 = target-num

            if num2 in seen:
                return [seen[num2], i]
            else:
                seen[num] = i

import unittest
class BasicTests(unittest.TestCase):

    testcases = [
        ([2,7,11,15], 9, [0,1]),
        ([3,2,4], 6, [1,2]),
        ([3,3], 6, [0,1])
    ]

    def test1(self):
        s = Solution()
        for nums, target, expected in self.testcases:
            actual = s.twoSum(nums, target)
            # print(actual, expected)
            assert actual == expected or list(reversed(actual)) == expected

if __name__ == "__main__":
    unittest.main()
Enter fullscreen mode Exit fullscreen mode

I have personally found this quite helpful and I hope you too will get some value from it. Good luck!

Top comments (0)