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
| |
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!
| |
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
| |
Reverse an array
| |
or
| |
Get odd positions of the array
| |
sum of objects in the array
| |
Get last object of the array
last object:
| |
second last object:
| |
For Else in Python
Use else with for when you want to do some processing if for loop completed without breaking
| |
Custom comparison between two objects
| |
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:
| |
Using
| |
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]
| |
stdin / stdout
Print to console without printing a new line
| |
Read input from stdin
| |
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.cacheas decorator, this caches in memory the result of a functional called with a particular set of arguments, which is memoization.1 2 3 4 5import functools @functools.cache def func_to_cache(num): # CODE GOES HEREFor
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