PyLeet Flashcards

(141 cards)

1
Q

How do you get a list of numbers in a particular range?

A

list(range(0,3))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you import Counter?

A

from collections import Counter

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you get the highest count item from a Counter?

A

ctr.most_common()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Initialize a list of “False” n times. 2 ways.

A

[False] * n

Or

[False for _ in range(n)]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Initialize a two dimensional list of [0] n * m times.

A

[[0]*n for _ in range(m)]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Where would one initialize a variable upon class instantiation?

A

def __init__():

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you loop through two arrays at once, side by side?

A

for i, j in zip(a, b):
print(i, j)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Diff between sort() and sorted()?

A

sort() sorts in place, sorted() returns a new list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How does one import components for heap operations?

A

from heapq import heapify, heappush, heappop

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do you initialize a heap?

A

heapify(my_list)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How do you add an element to a heap?

A

heappush(my_list, new_item)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How do you remove the next element from a heap?

A

heappop(my_list)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How to do integer division (no decimal or remainder)?

A

a//b

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How to get the first index of a specified character in a string?

A

s.index(‘e’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How to get the last index of a character in a string?

A

str.rfind.(‘e’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How to get the next index of a character after a given index in a string?

A

s.index(‘l’, 3)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How do you count the number of occurences of something in a list?

A

ls.count(1)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How do I replace part of a string?

A

s.replace(‘earl’, ‘world’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What are two ways to remove a particular item from a set?

A

fruits.remove(‘apple’), fruits.discard(‘apple’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How do you remove the last item from a list?

A

my_list.pop()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What’s the difference between the two ways to remove an item from a set?

A

remove throws an error if the item doesn’t exist, discard doesn’t

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How do you insert an item into a list at a certain index?

A

my_list.insert(3, “Apple”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How to initialize 2 variables at once?

A

x, y = 0, 0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How do you loop through the index and value of a list at the same time?

A

for i, v in enumerate(ls):

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
How do you loop through the key and value of a dictionary?
for k, v in d.items():
26
What happens if you enumerate a dictionary?
It loops through the index # and the keys, as if it were a list of keys.
27
What happens if you enumerate a dictionary.values()?
Loop through the list of values with index # and value.
28
What's the syntax for sorting a list of lists using sorted?
x = sorted(ls, key=lambda x: x[0]
29
What's the syntax for sorting via a custom sort function?
x = sorted(ls, key=lambda x: my_func(x))
30
What are two ways to reverse a list?
ls.reverse(), ls[::-1]
31
What is bitwise AND?
a & b
32
What is bitwise OR?
a | b
33
What is bitwise XOR?
a ^ b
34
What is bitwise NOT?
~a
35
What is bitwise left shift?
a << 1
36
What is bitwise right shift?
a >> 1
37
How do you display the bytes of an integer?
bin(n)[2:]
38
What's the difference between remove() and pop()?
remove() removes by value, pop() removes by index. If no argument is passed to pop(), it removes the last item in the list.
39
What's the fastest way to tally/ count the number of occurances of something in a list?
from collections import Counter Counter(myString/myList)
40
How does one import Counter?
from collections import Counter
41
How does one update a Counter with an additional list or string?
my_counter.update(new_list_or_string)
42
How does one access a counter value?
my_counter[key]
43
How do you loop through items in a Counter?
for k, v in my_counter.items()
44
How does one get the n most common items from a counter? What is the resultant format?
my_counter.most_common(2) : [(key1, count1), (key2, count2)]
45
How to import SortedList or SortedSet?
from sortedcontainers import SortedList
46
How to add an item to a SortedSet/List/
sorted_collection.add()
47
How to add multiple items to a SortedSet or SortedList?
sorted_collection.update()
48
how to drop an item from a SortedSet or SortedList?
sorted_collection.discard(value_to_remove)
49
Why does this code not work for initializing a multi dimensional array: [[False] * n] * m
It creates m rows all pointing to the same list, so that if you were to change the first item to True, then all first items of each row would appear to be True.
50
How does one unpack ("apple", "banana", "pear") into 3 variables at one?
f1, f2, f3 = my_fruits
51
Can you unpack only the first n items of a list of length n+ m? If so how?
Yes: a, b, *_ = my_list
52
Create simple lamba function to add two numbers?
add = lamba a, b: a+ b
53
How would one map a list of nums to a list of its squares?
squares = map(lambda x: x*x, nums)
54
How would one filter out even numbers from a list?
even = filter(lambda x: x%2==0, nums)
55
How would one use ANY to determine if any numbers are even?
any_even = any(x%2==0 for x in nums)
56
How would one use ALL to determine if all numbers are positive?
all_positive = all(x > 0 for x in nums)
57
Create a generator that yields items from the list my_nums.
gen = (n for n in my_nums)
58
What's the difference between tuple comprehension and creating a generator?
tuple comprehension say: tuple(x for x in iteratable), whereas a generator is (x for x in iterable)
59
Create a simple countdown generator using yield
def countdown_gen: while(n > 0): yield n n -= 1
60
Two ways to create a set?
my_set = set(), my_set = {1, 2, 3}
61
What does this create: my_set = {1, 2, 3, 1}
A set with only 1, 2, 3 (second instance of 1 is dropped)
62
Give an example of set comprehension creating a set with numbers 1-5
my_set = {n for n in range(1, 6)}
63
What is a type annotation?
Specifies the return type of a function: def multiply(a, b) -> int:
64
What datatype is used for decimals in python?
float
65
How does one initialize positive infinity?
float('inf')
66
What is the correct syntax for getting a sorted copy of a list in reverse order?
sorted_list = sorted(original, reverse=True)
67
How does one remove the first item from a python list?
item = my_list.pop(0)
68
How does one loop the range 1-5 reversed? (2 ways)
1. for i in reversed(range(1,6)): 2. for i in range(5,0,-1):
69
What are 3 ways to copy a list in python?
1. new_list = orig[:] 2. new_list = list(orig) 3. from copy import copy new_list = copy(orig)
70
What happens if you enumerate a string in python?
for i, ch in enumerate(s): loops through both the index and character.
71
What python data structsure can be used on a LRU type cache and why?
OrderedDict, because it tracks the order of the entries into the dictionary.
72
How does one import OrderedDict?
from collection import OrderedDict.
73
How does one move an item in an OrderedDict to the end of the dictionary?
my_dict.move_to_end(key)
74
How does one move an item in an OrderedDict to the beginning of the dictionary?
my_dict.move_to_end(key, last=False)
75
How does one import SortedList?
from sortedcontainers import SortedList
76
How does one give a custom sort function to a SortedList?
def my_sort_func(x): return x[1] custom_sl = SortedList(key=my_sort_func)
77
How does one view the first member of a SortedList?
sorted_list[0]
78
How does one remove the first element of a SortedList?
sorted_list.pop(0)
79
What does __slots__ do?
Allocates memory slots on a class instance.
80
Show can example of slots statement for rows and columns on a class instance.
__slots__ = ("rows", "columns")
81
What python method checks if a character is a letter?
ch.isalpha()
82
How to check if a character is a number in python?
ch.isdigit()
83
How do check if a character is alphanumeric in python?
ch.isalnum()
84
How might one filter out no alhpanumeric characters using filter()?
new_string = "".join(filter(lambda ch:ch.isalnum(), my_str))
85
What are 3 ways to append two lists in python?
1. orig += additional_list 2. combined = l1 + l2 3. orig,extend(additional_list)
86
What's the difference between set comphrehensions and dictionary comprehensions in python?
Both use {}, but dict comp uses {k:v for k in iterable} while set comp uses {k for jk i iterable}
87
What would be a way to map a list of numbers to their percentage of the sum total? (use map)
total = sum(nums) pcts = list(map(lambda x : x/total, nums))
88
How does one sort a list in place?
my_list.sort()
89
What's the most efficient data structure for operations at the beginning and end of a list? How to import?
from collection import deque
90
What are the 4 main ops of a deque?
pop() - remove from end popleft() - remove from beginning append() - add item to end appendleft() - add to front of list
91
How does one instantiate a deque?
from collections import deque my_deque = deque() elements (from an iterable, like a list) initial_elements = [1, 2, 3, 4, 5] my_deque_with_elements = deque(initial_elements)
92
What is the result of `5&3`?
011 & 101 = 001 == 1
93
What is the result of `5 | 3`?
011 or 101 = 111 == 7
94
What is the result of `5^3`
011 not-or 101 = 110 = 6
95
What is the result of ~5
010 = 2
96
What does a not operator do?
Flips the bits
97
How does exclusive OR work in python?
Only becomes true if one OR the other bit is true.
98
What is the exclusive or operator in python?
the caret symbol (^)
99
What is 5 << 1?
101 shifted left one bit = 1010 = 10
100
What is 5 >> 1?
101 shifted right one bit = 010 = 2
101
What's the fastest way to integer dive by 2 in python?
x >>= 1
102
Can you left shift in place?
x >>=1
103
Can you right shift in place?
x >>= 1
104
Describe how to find the minimum spanning tree (minimium weights to connect all graph nodes) (Krustkal)
1. Sort graph by edges 2. Create a parent table of length N (vertices) 3. Loop through edges, track the parents of each V, and add any edge that isn't in a connected subgraph.
105
What is the big O complexity of Kruskal's algo (Min Spanning Tree?) Why?
E * log(E) # of edges Sort edges = e*log(e) loop through n
106
What's another MST, Prim's?
1. Make a dict of all nodes/weights to each node. 2. Start arb node, heapify weights of that node. 3. Choose lowest weight, add that to MST, then add remaining nodes from that node to the heap
107
How do you remove the first item of an OrderedDict?
my_ordered_dict.popitem(last=False)
108
How do we sort a list of 3 numbers? [[1,2,3], [2,3,4], [1,0,2]]
my_list.sort(key = lambda x: (x[0], -x[1], x[2]))
109
in python how do you import deque?
from collections import deque
110
How do you instantiate a deque?
my_deque = deque()
111
What is the exponentiation operator in python?
** for example, 2**3 = 8 (2 to the 3rd) 4**.5 = 2
112
How can one take the square root in python? 2 ways
1. Exponentiation n**.5 2. math.sqrt() (import math)
113
What are two ways to tell if something is a number in python?
1. type(variable) in (int, float) 2. isinstance(variable, (int, float))
114
What is the keyword for a boolean in python?
"bool"
115
How to use "max integer" or "max value" in python?
float('inf')
116
What is the import for a heapq in python?
import heapq
117
In fact, anytime we are tasked with finding the k (or k th ) [smallest/largest/etc.] element(s), we should always consider whether the
Quickselect Algorithm
118
Which leetcode type problems use quick sort or quick select?
typically involve the need for efficient sorting or finding the k-th smallest/largest element in an array or list.
119
What types of problems use prefix sums?
Range Sum Queries, Subarray Sum Problems, Difference-Based Problems: Analyze cumulative differences, Binary Array Problems: Count 1s or balance 0s/1s in subarrays.
120
What pattern is best for range sums?
prefix sums
121
What pattern is best for subarray sums?
prefix sums
122
How to tell if a python character is alphabetical? ( a letter)
char.isalpha() -> boolean
123
How to check in python if a character is alpha numeric?
mychar.isalnum()-> boolean
124
What is wrong with this initialization? visited = [[False] * width] * height
It creates 3 references to the exact same list rather than 3 independant lists.
125
What is the time complexity of finding permutations?
O(N!)
126
What is the algorithm for finding all permutations
Backtracking/Recursion
127
How do you construct the next largest permutation given a permutation?
1. Loop backwards, find the first two decreasing numbers 2. loop again and find the first number larger than the swap index. Swap them 3. Reverse everything to the right of that string
128
How do I pop from the left and right sides of a typical python array? ex [1,2,3]
arr.pop() -> rightmost arr/pop() -> leftmost
129
How can I compare an int to a float in python?
my_int == my_float, python will handle it
130
Is this valid syntax? from collections import heapq
No. From heapq import heappushpop, heapify, heappop
131
What's wrong with this syntax? heap_nums = heapq.heapify(nums[:k])
from heapq import heapify my_list = [nums:k] heapify(my_list)
132
What's wrong with this syntax? heappushpop(nums[i], sorted_nums)
Backwards parms: heappushpop(sorted_nums, nums[i])
133
What python data structure is helpful for anagrams?
Counter
134
When should a python Counter be used?
Frequency Tallying, Top K frequency, sliding window.
135
python fastest way to make a sortedset out of sorted containers.
from sortedcontainers import SortedSet my_list = [3,2,1] my_sorted_list = SortedSet[3,2,1]
136
How to trim whitespaces from a string in python?
trimmed = my_string.strip()
137
How do you sort a list of lists by the 3nd then 3rd elements in the lists?
trips = sorted(trips, key=lambda x: (x[1], x[2]))
138
What's wrong with this? sorted(trips, key=lambda x: x[1], x[2])
The key argument in sorted() expects a single function that returns a value (or a tuple of values).
139
If this get's me a character's index, how do I go backwards to get the character from a number? ord(ch) - ord('a')
chr(number + ord('a'))
140
What's the input of ord() and the reverse operation of ord()?
A character, chr()
141
What's the input of chr() and the reverse operation of chr()?
A number, ord()