Python Cheat Sheet Made by Abdul Malik
Python Cheat Sheet Made by Abdul Malik
Data Structures
Important data structures for Leetcode
Lists
nums = [1,2,3]
dict = {'a':1,'b':2,'c':3}
# Initialization
Counter(list1) # => Counter({'x': 4, 'y': 2, 'z': 2})
Counter("Welcome to Guru99 Tutorials!") # => Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2.....})
# Updating
counterObject = collections.Counter(list1)
counterObject.update("some string") # => Counter({'o': 3, 'u': 3, 'e': 2, 's': 2})
counterObject['s'] += 1 # Increase/Decrease frequency
# Accessing
frequency_of_s = counterObject['s']
# Deleting
del couterObject['s']
Deque
A double-ended queue, or deque, has the feature of adding and removing elements from either end.
queue = deque(['name','age','DOB'])
nums = [5, 7, 9, 1, 3]
heapq.heapify(nums) # converts list into heap. Can be converted back to list by list(nums).
heapq.heappush(nums,element) # Push an element into the heap
heapq.heappop(nums) # Pop an element from the heap
#heappush(heap, ele) :- This function is used to insert the element mentioned in its arguments into heap. The order is adjusted, so as heap structure is maintained.
#heappop(heap) :- This function is used to remove and return the smallest element from heap. The order is adjusted, so as heap structure is maintained.
set = {1,2,3}
set.add(item)
set.remove(item)
set.discard(item) | set.remove(item) # removes item | remove will throw error if item is not there, discard will not
set.pop() # removes random item (since unordered)
set.union(anotherSet) # ...
set.update(anotherSet) # adds anotherSet without duplicate
A tuple is a collection which is ordered, unchangeable and can contain duplicate values
tuple = (1,2,3,1)
** map(fun, iter) **
#fun : It is a function to which map passes each element of given iterable.
#iter : It is a iterable which is to be mapped.
** zip(list,list) **
for elem1,elem2 in zip(firstList,secondList):
# will merge both lists and produce tuples with both elements
# Tuples will stop at shortest list (in case of both lists having different len)
** enumerate(list|tuple) **
# [when you need to attach indexes to lists or tuples ]
enumerate(anyList) # ['a','b','c'] => [(0, 'a'), (1, 'b'), (2, 'c')]
** filter(function|list) **
filter(myFunction,list) # returns list with elements that returned true when passed in function
** bisect.bisect(list,number,begin,end) ** O(log(n))
# [ returns the index where the element should be inserted
# such that sorting order is maintained ]
a = [1,2,4]
bisect.bisect(a,3,0,4) # [1,2,4] => 3 coz '3' should be inserted in 3rd index to maintain sorting order
The above 3 functions are exact same of bisect.bisect(), the only difference
is that they return the sorted list after inserting and not the index. The
left() right() logic is also same as above.
** ord(str) **
# returns ascii value of the character , Example ord("a") = 97
** chr(int) **
#return character of given ascii value , Example chr(97) = "a"