Python
Cheatsheet
Iteration
Iterate Array with Index
my_array = [1, 2, 3, 4, 5]
for index, element in enumerate(my_array): print(index, element)
Iterate Array/String
my_string = "Hello, World!"
for char in my_string: print(char)
Loop
while list1 or list2: # do something if list1 or list2 are not empty
for i in range(6): print(i) # will print 0 to 5
Array
Basic Array Operations
arr = [1, 2, 3, 4, 5]
print(arr[::-1])# [5, 4, 3, 2, 1]
print(arr[2:])# [3, 4, 5]
print(arr[:2])# [1, 2]
# create array with value of 0 and length of 10arr = [0] * 10
Map/Dictionary
Basic Dictionary Operations
my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
# get key
# if key1 not exists, will return default_valuemy_dict.get('key1', 'default_value')
my_dict['key1']my_dict['key1_notexists'] # will raise KeyError if not exists
# delete elementdel my_dict['key2']
# get all valuesmy_dict.values()
# get all keysmy_dict.keys()
Check Key/Value Exists in Dictionary
my_map = {"key1": 1, "key2": 2, "key3": 3}
# Check if a key exists in the mapif "key2" in my_map: print("Key 'key2' exists in the map")
# Check if a value exists in the mapif 2 in my_map.values(): print("Value 2 exists in the map")
Default Value for Dictionary
from collections import defaultdict
# Function to return a default# value for keys that are not# presentdef def_value(): return "Not Present"
# Defining the dictd = defaultdict(def_value)d["a"] = 1d["b"] = 2
print(d["a"]) # 1print(d["b"]) # 2print(d["c"]) # Not Present
Set
Basic Set Operations
hashset = set()
# Adding elements to the hash sethashset.add(5)hashset.add(10)hashset.add(15)
# Checking if an element exists in the hash setif 10 in hashset: print("10 exists in the hash set")
# Removing an element from the hash sethashset.remove(5)
# Iterating over the hash setfor element in hashset: print(element)
Stack
Basic Stack Operations
stack = []
stack.append(1) # Pushes 1 onto the stackstack.append(2) # Pushes 2 onto the stack
top_element = stack.pop() # Removes and returns the top elementprint(top_element) # Outputs: 2
if len(stack) == 0: print("Stack is empty")
if not stack: print("Stack is empty")
Bit and Binary Operations
# XOR1 ^ 2 # 1 XOR 2 -> 3 (BINARY: 1 XOR 10 -> 11)
# right bitwise8 >> 1 # 1000 -> 4 (BINARY: 1000 shift to right 1 time -> 100)7 >> 1 # 111 -> 3 (BINARY: 111 shift to right 1 time -> 11)
# bit mask8 & 1 # 1000 AND 1 -> 03 & 1 # 11 AND 1 -> 1
n = 0print(n | 1) # add 1 to right most bit
a = 42print(bin(a)) # 0b101010
Helpful Functions
Math Functions
max(a, b)min(a, b)
# absolutea = -12print(abs(a)) # 12
# powerprint(2 ** 4) # 16
# divisiona = 5print(a / 2) # 2.5print(a // 2) # 2
String Functions
"string".islower() # is lowercase"string".isdigit() # is number"string".isalpha() # is string"string".isalnum() # is number or string
"string".lower() # lowercase
Sorting
a = [1, 3, 4, 2]
# this will change the a directly and return nothinga.sort()print(a) # [1,2,3,4]
a.sort(reverse=True)print(a) # [4,3,2,1]
print(sorted(a)) # [1,2,3,4]
# custom sort logicpoints = [[1, 2], [3, 4]]
def logic(e: List[int]): return e[0]**2 + e[1]**2 # a^2 + b^2
print(sorted(points, key=logic))
Conditional Logic
# if logicif a < b < c: print(b)
# ternaryx = 5result = "Even" if x % 2 == 0 else "Odd"print(result) # Odd
# select element from tuplea = 1b = 2c = (a, b)[a > b]# (a, b) -> array [a,b]# [a > b] -> True will be index 1, False will be index 0
print(c) # 2
Counter
from collections import Counter
a = "hello world!"print(Counter(a))# Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1, '!': 1})
Sort
Sort by Value and Key in Decreasing Order
class Solution: def frequencySort(self, nums: List[int]) -> List[int]: dic = Counter(nums) nums.sort(key=lambda x: (dic[x], -x)) return nums