Frequently used Python code blocks and gists

A collection of frequently used python code blocks and gists

Converting data types

Get binary equivalent of integer

The bin() method converts and returns the binary equivalent string of a given integer.

Alternatively, you can also check the problem to convert num to binary.

Get integer when dividing float

1
a = num//div

Array

Initialise an array of n length

Initialise an array of n length with 0: arr = [0] * n

Initialise a two-dimensional array

Don’t use [[v]*n]*n, it is a trap!

1
2
3
4
5
6
>>> a = [[0]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0]=1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]

but t = [ [0]*3 for i in range(3)]

works great.

Get Value at Index

To handle array indices in case INF needs to be handled

1
2
3
4
5
6
7
8
def get_value_at_index(arr, i):
    if i >= 0:
        if i < len(arr):
            return arr[i]
        else:
            return float("inf")
    else:
        return -float("inf")

Reverse an array

1
nums = nums[::-1]

or

1
nums.reverse() #this will reverse and update nums

Get odd positions of the array

1
nums[1::2]

sum of objects in the array

1
2
3
a = range(10)
# [0,1,2,3,4,5,6,7,8,9]
b = sum(a)

Get last object of the array

last object:

1
nums[-1]

second last object:

1
nums[-2]

For Else in Python

Use else with for when you want to do some processing if for loop completed without breaking

1
2
3
4
5
6
for i in mylist:
    if i == theflag:
        break
    print(i)
else:
    print("for loop completed without any break")

Custom comparison between two objects

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import functools

def mycmp(a, b):
  print("comparing ", a, " and ", b)
  if a > b:
      return 1
  elif a < b:
      return -1
  else:
      return 0

print(min([45, 78, 813], key=functools.cmp_to_key(mycmp)))
print(max([45, 78, 813], key=functools.cmp_to_key(mycmp)))

Eg:
Given a list of numbers in string format, you want to construct the biggest number out of it ["99", "990"]
Solution is to sort in decreasing order and append the numbers, but python’s sort won’t work for the above case

Custom max

Using lambda:

1
2
lis = ['1','100','111','2', 2, 2.57]
max(lis, key=lambda x: int(x))

Using

1
2
test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key=test.count))

Reverse array or string

  • Reverse a string: a[::-1]
  • Reverse partial string: a[2:4] = a[2:4][::-1]

Repeat string n times

Repeat string x n times: x*n

Sort of indices

Below will generate numbers [0..(len(counts)-1)] and then sort it basis value of count[k]

1
sorted(range(len(counts)), key=lambda k: counts[k])

stdin / stdout

1
2
# ends the output with a <space>
print("Hello World", end=' ')

Read input from stdin

1
2
3
# Read comma separated integers from stdin
# 3,4,-1 , 4,5
arr = list(map(int, input().split(',')))

In dictionary keys are unordered

d.keys() gives key in the order they were added
Use sorted(d.keys()) for ordered keys

Memoization

  • For Python 3.9+
    Use @functools.cache as decorator, this caches in memory the result of a functional called with a particular set of arguments, which is memoization.

    1
    2
    3
    4
    5
    
    import functools
    
    @functools.cache
    def func_to_cache(num):
        # CODE GOES HERE
    
  • For Python 3.2+
    Use @functools.lru_cache(maxsize=None) as decorator. By default @functools.lru_cache() only caches the 128 most recently used calls.

    1
    2
    3
    
    @functools.lru_cache(maxsize=None)
    def func_to_cache(num):
        # CODE GOES HERE