Patterns Flashcards
(93 cards)
INSTRUMENT:
How to check if the type of an object is a list?
lista = [1,2,3] if type(lista) is list: return list
INSTRUMENT:
How to create a personalizable function for comparing?
We need to use functools!
import functools
#then we define a compare function def compare(item1, item2): if item1 < item2: return 1 # lo metto dopo elif item1 > item2: return -1 # lo metto prima else: return 0 #se sono consideration uguali
#calling lista = [1, 4, 3, 2] sorted(lista, key=functools.cmp_to_key(compare))
INSTRUMENT:
What do I do if I want to know where an element in a sorted list should be placed?
Use bisect/bisect_left!
from bisect import bisect_left #from bisect import bisect_right
l1 = [2,3,5] bisect_left(l1, 3) #returns 1! #bisect(l1, 3)
ALGORITHM: briefly describe merge sort and implement it
merge sort algorithm
Merge sort is basically based on split thw tho halfs recursively and then merge them. Comp time of O(nlogn)
Algo:
def merge(left, right, A): lc, rc = 0, 0 while lc < len(left) and rc < len(right): if left[lc] <= right[rc]: A[lc + rc] = left[lc] lc += 1 else: A[lc + rc] = right[rc] rc += 1
if lc == len(left): A[lc + rc: -1] = right if rc == len(right): A[lc + rc: -1] = left return A
def mergeSort(A): if len(A) <= 1 : return A
left = mergeSort(A[0:len(A)//2]) right = mergeSort(A[len(A)//2: -1]) return merge(left, right, A)
mergeSort([4,2,5])
CODE SNIPPET:
Can you convert an integer in a list with list(num)?
NO! integer is not an iterable, you need to cast to string before: num = 978 num = str(num) num = list(num) num = [int(i) for i in num]
INSTRUMENT, BINARY: how to convert a number to a binary number?
#we can use format built in function num = 27 num = format(num, 'b') #at this point is a binary string! num = list(num) #now that this is a list we can work on it!
INSTRUMENT, BINARY: how can you do left shift or right shift? what are the results? what do they mean mathematically?
left shift
a = 5
a «_space;1 #from 101 to 1010 –> from 5 to 10
a «_space;2 #from 101 to 10100 –> from 5 to 20
#shifting a number is like multiply it for 2 elevated at number of shifts
a = 5
a»_space; 1 #from 101 to 10 –> from 5 to 2
a»_space; 2 #from 101 to 1 –> from 5 to 1
#shifting numers right is like divide per due elevated at number of shifts (// division)
INSTRUMENT, BINARY: if I have to evaluate every single bit of a number where could I store the result?
In a list of 32 elements, given that a binary number usually does not exceed 32 bits
INSTRUMENT, STRINGS: how can I compare chars values (even numbers) to sort them?
you can use ord(‘a’) or ord(‘9’)
CODE SNIPPET: what is Hamming distance? How do we calculate it?
Hamming distance is the number of different bits for two given numbers. You can just do xor between the two numbers and count the numbers of 1's of the result. a = 5 b = 6 res = format(a ^ b, 'b') for i in range(len(res)): if res[i] == '1': count += 1
CODE SNIPPET: given two numbers how con you find GCD (greatest command divisor)?
You can use Euclidean Algorithm:
’’’
let A,B with A >= B
compute: A mod B = R let A = B, B = R repeat steps till B = 0
return B (before it becomes 0) '''
INSTRUMENT, STRINGS:
I have a list, I want to convert it to a string. How do I do that?
I use join:
a = [‘c’, ‘i’,’a’,’o’]
‘‘.join(a) –> ‘ciao’
PATTERN: I need to find a value, I can find a min value and a max value, so define a search space. What do I use?
BINARY SEARCH:
def bin_src(array, num, left, right):
if left > right:
return -1
mid = left + ((right - left) // 2) #avoid integer overflows (in python is not necessary anyway…)
if array[mid] == num:
return mid
elif array[mid] > num: return bin_src(array, num, left, mid-1)
else: return bin_src(array, num, mid+1, right)
bin_src([1,2,5], 5, 0, 2)
CODE SNIPPET: Given 3 values, B, C and N with N > B, C: how can we encode the two values in a single one, then extract them?
We use moltiplication and module:
B = 4 C = 5 N = 7
A = B + (C*N)
print(f’B is {A%N}’)
print(f’C is {A // N}’)
INSTRUMENT, STRINGS: I need a dictio with all alphabet letters with the value set to i = 0. How do I do that with a single line of code?
import string
i = 0 d = dict.fromkeys(string.ascii_lowercase, i) #crea le chiavi (quella funzione genera una stringa che e tutto l alfabeto) e da come value i a tutti
INSTRUMENT: how can i find max and min of a list?
lista = [1,2,3]
min(lista)
max(lista)
PATTERN: 2sum implement it, which pattern do I use?
Use two pointers not sort (from 3sum you sort).
#2sum class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: w = {} for i in range(len(nums)): w[nums[i]] = i
for i in range(len(nums)): B = target - nums[i] if B in w and w[B] != i: return [i, w[B]]
Can I modify the index of a for cycle?
Yes, but with bad consequences. Do not do that ! (use a while instead)
CODE SNIPPET: given list find all contiguous subarrays
def solve(A): res = 0 subs = [] for i in range(len(A)): subs.append([A[i]]) new_sub = [A[i]] for j in range(i+1, len(A)): new_sub.append(A[j]) subs.append(list(new_sub))
return subs
solve([3,4,5])
PATTERN 3SUM: what do I do? Comp time?
I use 2 pointers + sorting list. Comp time of O(n^2)
#3sum (that gives zero)
‘’’
-devi ordinare la lista (tanto il tempo viene mangiato da O(n^2))
-numero per numero e intanto usi il two pointers technique (2 sum with ordered list)
-scorri nel for principale e skippa i numeri uguali per evitare i duplicati
-se trovi una tripla che fa il target, aumenta left e continua ad aumentarlo finche non e un valore diverso
‘’’
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
res = []
for i in range(len(nums)-2):
if i != 0 and nums[i] == nums[i-1]:
continue
l, r = i+1 , len(nums) - 1
tgt = -nums[i]
while l < r:
if nums[l] + nums[r] == tgt:
res.append([nums[i], nums[l], nums[r]])
l += 1
while nums[l] == nums[l-1] and l < r:
l += 1
elif nums[l] + nums[r] > tgt: r -= 1 else: l += 1 return res
QUESTION: I need to find all the possible sub arrays with a given property. I find a new value that gives me all other possible combinations with that value: what do I do?
I do not sum +1, I sum (r - l + 1)
INSTRUMENT: I have a binary number, how do I convert it in decimal?
a = '000100' a = int(a, 2)
INSTRUMENT: I want to insert an element in a list at a certain index. What do I do?
lista = [1,2,3,4,5]
lista.insert(‘b’, 2)
#ottengo [1,2,’b’,3,4,5]
INSTRUMENTS, STRINGS:
- check if a string is of all digits
- check if a string is of all characters
- check if a string is only lower characters
- check if a string is only upper characters
- convert strings to upper
- convert strings to lower
string lowercase and uppercase check
#check if a string is composed only by digits (so check if it is a number) '0130'.isdigit() #True '000'.isdigit() #True '-'.isdigit() #False 'A09'.isdigit() #False
#check if a string is composed only by alphabet characters 'A'.isalpha() #True 'a'.isalpha() #True 'As'.isalpha() #True 'A1'.isalpha() #False 'Aaksdjcoasdi'.isalpha() #True 'As#'.isalpha() #False
‘AAA’.islower() #False
‘aaA’.islower() #False
‘aa1’.islower() #True! Numbers are considered ‘neutral’
‘aa#’.islower() #True! any other simbol that is not alpha is neutral
‘AAA’.isupper() #True
‘aaA’.isupper() #False
‘AA1’.isupper() #True
‘AA$’.isupper() #True
‘aSd2’.upper() #ASD2
‘aSd2W#’.lower() #asd2w#