Basics
Data Types
Operators and it’s precendence
Data Structures
Important data structures for Leetcode
Lists
Lists are used to store multiple items in a single variable
Operations Time Complexities
|
|
|
|
Dictionary
Dictionaries are used to store data values in key:value pairs. Info about collections.Counter() available below.
Operations Time Complexities
|
|
Counter
Python Counter is a container that will hold the count of each of the elements present in the container. The counter is a sub-class available inside the dictionary class. Specifically used for element frequencies
Pretty similar to dictionary, infact I use defaultdict(int) most of the time
|
|
Deque
A double-ended queue, or deque, has the feature of adding and removing elements from either end.
Operations Time Complexities
|
|
Heapq
As we know the Heap Data Structure is used to implement the Priority Queue ADT. In python we can directly access a Priority Queue implemented using a Heap by using the Heapq library/module.
Operations Time Complexities
|
|
Sets
A set is a collection which is unordered, immutable, unindexed, No Duplicates.
Operations Time Complexities
|
|
Tuples
A tuple is a collection which is ordered, unchangeable and can contain duplicate values
Operations Time Complexities
Similar to list
|
|
Strings
|
|
Built-in or Library functions
Functions to iterate over list / other iterable (tuple, dictionaries)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
** 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) #Example ''' a = ("John", "Charles", "Mike") b = ("Jenny", "Christy", "Monica") x = zip(a, b) #use the tuple() function to display a readable version of the result: print(tuple(x)) o/p: (('John', 'Jenny'), ('Charles', 'Christy'), ('Mike', 'Monica')) ''' ** any(list) ** [ OPPOSITE IS => ** all() ** ] any(someList) # returns true if ANY element in list is true [any string, all numbers except 0 also count as true] ** 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 ***************** import bisect *********************** ** 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] => 2 coz '3' should be inserted in 2nd index to maintain sorting order # Other variants of this functions are => bisect.bisect_left() | bisect.bisect_right() # they have same arguments. Suppose the element we want to insert is already present # in the sorting list, the bisect_left() will return index left of the existing number # and the bisect_right() or bisect() will return index right to the existing number # ** bisect.insort(list,number,begin,end) ** O(n) to insert # ** bisect.insort_right(list,number,begin,end) ** # ** bisect.insort_left(list,number,begin,end) ** 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.
Getting ASCII value of a character
1 2 3 4
** ord(str) ** # returns ascii value of the character , Example ord("a") = 97 ** chr(int) ** #return character of given ascii value , Example chr(97) = "a"
Clean Code Tips
Doc Strings - Documentation for your functions in the interview to look slic 😎
A docstring is short for documentation string.
Python docstrings (documentation strings) are the string literals that appear right after the definition of a function, method, class, or module.
Triple quotes are used while writing docstrings. For example:
1 2 3
def double(num): """Function to double the value""" return 2*num
Docstrings appear right after the definition of a function, class, or a module. This separates docstrings from multiline comments using triple quotes.
The docstrings are associated with the object as their
__doc__
attribute.So, we can access the docstrings of the above function with the following lines of code:
1 2 3 4
def double(num): """Function to double the value""" return 2*num print(double.__doc__)
Output
1
Function to double the value
Use Assert keyword in python for testing edge cases. Looks more professional.
Definition and Usage
The
assert
keyword is used when debugging code.The
assert
keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError.You can write a message to be written if the code returns False, check the example below.
1 2 3 4
x = "hello" #if condition returns False, AssertionError is raised: assert x == "goodbye", "x should be 'hello'"
ALWAYS be aware of any code snippet that is being REPEATED in your solution. MODULARITY #1 Priority. Refactoring is also an important part of interview.
- This is usually asked as a follow up after coding the solution. Are there any changes you want to make to this solution?
Miscellaneous
How to take multiple line input in python?
- Using split() method
- Using List comprehension
Syntax :
1
input().split(separator, maxsplit)
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
# Python program showing how to # multiple input using split # taking two inputs at a time x, y = input("Enter a two value: ").split() print("Number of boys: ", x) print("Number of girls: ", y) print() # taking three inputs at a time x, y, z = input("Enter a three value: ").split() print("Total number of students: ", x) print("Number of boys is : ", y) print("Number of girls is : ", z) print() # taking two inputs at a time a, b = input("Enter a two value: ").split() print("First number is {} and second number is {}".format(a, b)) print() # taking multiple inputs at a time # and type casting using list() function x = list(map(int, input("Enter a multiple value: ").split())) print("List of students: ", x)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
# Python program showing # how to take multiple input # using List comprehension # taking two input at a time x, y = [int(x) for x in input("Enter two value: ").split()] print("First Number is: ", x) print("Second Number is: ", y) print() # taking three input at a time x, y, z = [int(x) for x in input("Enter three value: ").split()] print("First Number is: ", x) print("Second Number is: ", y) print("Third Number is: ", z) print() # taking two inputs at a time x, y = [int(x) for x in input("Enter two value: ").split()] print("First number is {} and second number is {}".format(x, y)) print() # taking multiple inputs at a time x = [int(x) for x in input("Enter multiple value: ").split()] print("Number of list is: ", x) # taking multiple inputs at a time separated by comma x = [int(x) for x in input("Enter multiple value: ").split(",")] print("Number of list is: ", x)
1 2 3 4 5 6 7 8 9
Syntax : math.log(a,Base) Parameters :a : The numeric value Base : Base to which the logarithm has to be computed. Return Value : Returns natural log if 1 argument is passed and log with specified base if 2 arguments are passed. Exceptions : Raises ValueError is a negative no. is passed as argument.
1 2 3 4 5 6 7 8 9
import math # Printing the log base e of 14 print ("Natural logarithm of 14 is : ", end="") print (math.log(14)) # Printing the log base 5 of 14 print ("Logarithm base 5 of 14 is : ", end="") print (math.log(14,5))
- Finding the ceiling and the floor value
- Ceil value means the smallest integral value greater than the number and the floor value means the greatest integral value smaller than the number. This can be easily calculated using the ceil() and floor() method respectively.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Python code to demonstrate the working of # ceil() and floor() # importing "math" for mathematical operations import math a = 2.3 # returning the ceil of 2.3 (i.e 3) print ("The ceil of 2.3 is : ", end="") print (math.ceil(a)) # returning the floor of 2.3 (i.e 2) print ("The floor of 2.3 is : ", end="") print (math.floor(a))
- Other Important functions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#Constants # Print the value of Euler e (2.718281828459045) print (math.e) # Print the value of pi (3.141592653589793) print (math.pi) print (math.gcd(b, a)) print (pow(3,4)) # print the square root of 4 print(math.sqrt(4)) a = math.pi/6 b = 30 # returning the converted value from radians to degrees print ("The converted value from radians to degrees is : ", end="") print (math.degrees(a)) # returning the converted value from degrees to radians print ("The converted value from degrees to radians is : ", end="") print (math.radians(b))
1 2 3 4 5 6
** bin(int) ** bin(anyNumber) # Returns binary version of number ** divmod(int,int) ** divmod(dividend,divisor) # returns tuple like (quotient, remainder)
How the custom comparator works
When providing a custom comparator, it should generally return an integer/float value that follows the following pattern (as with most other programming languages and frameworks):
- return a negative value (
< 0
) when the left item should be sorted before the right item - return a positive value (
> 0
) when the left item should be sorted after the right item - return
0
when both the left and the right item have the same weight and should be ordered “equally” without precedence
1 2 3 4 5 6 7 8 9 10 11
from functools import cmp_to_key sorted(mylist, key=cmp_to_key(compare)) #Example def compare(item1, item2): if fitness(item1) < fitness(item2): return -1 elif fitness(item1) > fitness(item2): return 1 else: return 0
Python integer division behaves differently with -ve numbers ex: -3//2 will give -2 answer instead of -1 so always use int(-3/2) for integer division in problems
Resources
The Modulo Operation (%) With Negative Numbers in Python