Python Flashcards
Strings mutable?
No, immutable. If you want to concat a bunch of strings without creating a new string for each intermediate operation, use ““.join(list)
Returns true if all char are alphanumeric (and at least one char)
isalnum()
Returns true if all char are letters (and at least one char)
isalpha()
Returns true if all char are digits (and at least one digit)
isdigit()
Returns a string which is a concatenation of the strings in a list (or other iterable)
join
““.join
Split a string on whitespace, ignore empty strings
split no param
That means splitting an empty string will return an empty list
Split a string on whitespace, include empty string
split(‘ ‘)
Remove leading and trailing whitespace
strip
Add an element to list
append
If you’re trying to create a list of lists, use append rather than +=
Combine two lists
+ or += joins two lists into a single list
append adds a single element to a list. that’s why you want to use append to compose a list of lists.
extend is an in-place function call so you should return the original list
set operations
set()
add, remove
list pop no argument
removes the last item in the list
get k,v from map
items()
Returns a dict_items object which is not accessible via index.
Need to use operator.getitem()
sort
list.sort(). returns None. operates on a list, in place, stable, does not return new list b/c it’s an in place sort, key arg takes a fn that extracts a comparison key
convert comparator to key
func_tools.cmp_to_key
sorted
sorted(list)
built in method.
returns new sorted list.
stable.
key arg takes a function that extracts a comparison key from a single element.
sorted(list, key=len)
sorted(list, key=abs)
class defn
The purpose of the init method is to initialize the object’s attributes. Used in classes only.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
return the key corresponding to the max val in a freq map
max(freq_map.items(), key=operator.itemgetter(1))[0]
f = operator.itemgetter(2)
what does f(‘ABC’) return
Returns C, the item at index 2
g = operator.itemgetter(2, 5, 3)
what does g(‘ABCDEF’) return?
Returns a list with the items at indicies 2, 5, and 3
(‘C’, ‘F’, ‘D’)
initialize dict
defaultdict(int)
remove first element of list
list.pop(0)
O(n)!
Use deque instead
reverse a list
list[::-1]
list.reverse() does it in place. can’t assign a return value.
list.reversed() returns a new reversed list.
pop vs get for map
pop will throw a KeyError is no default is provided and the key is not found
max int
MAX SIZE
from sys import maxsize
sys.maxsize or sys.maxsize - 1
sort ascending
list.sort()
In place
l1.extend(l2)
Adds the second list to the first list in place. Returns None. Need to return l1 for the combined list.
python deque
from collections import deque
deque()
deque.append()
deque.appendleft()
can’t pop from empty deque! use len to check
deque.pop()
deque.popleft()
Initialize array fixed value
dp = [None] * n
dp = [float(‘inf’)] * n
dp = [float(‘-inf’)] * n
How do you solve dynamic programming problems?
- Use an array to capture state. So dp[i] represents the state of the system at i. The number of steps require to get to the ith step. The minimum number of coins needed to make the amount i. The length of the longest subsequence ending with the ith element.
- Determine a function to transition between elements. If know dp[i], how do I calculate dp[i+i]?
- Base case. How do we get started? Usually one or zero but can be tricky.
How do you identify dynamic programming problems?
- Asking for max or min of something, particularly the max or min number of combinations (but not all max/min problems require dynamic programming e.g. stock trade)
- Having to calculate state based on a previous state (longest subsequence, for example)
import types such as List
from typing import List
are collections hashable? can they be used as a key in hashmaps?
No. Use tuple instead.
create list from dict_values
list(dict_values)
create defaultdict
from collections import defaultdict
defaultdict(int)
defaultdict(float)
defaultdict(str)
defaultdict(list)
can do other fancier things like a lambda function
call class
s = Solution()
s.method()
import Counter
from collections import Counter
pass func to sort
list.sort(lambda x: x[0])
Combine a list of lists
Use + instead of append!
Sort descending
list.sort(reverse=True)
How many unicode characters are there?
More than a million
how do you convert the right-most bit to zero?
AND n & n-1
Binary Search Time Complexity
O(log n)
Collection must be ordered
divmod
divmod(n, 3) returns (result of division by 3, remainder)
heap operations
Import heapq
heap = []
Heapq.heapify(heap)
Heapq.heappush(h, value)
Heapq.heappop(h)
while heap
nlargest
nsmallest
heap[0]
smallest value
python heap implementation is min heap
how to think about dict.items
iterable (k,v) tuple
basically only good for for (k,v) in dict
can also use with max/min/sort(key=operator.itemgetter(0 or 1))[0 or 1]
not itemgetter has no _
no itemgetter is a fn that uses ( not [
how do you delete a key in a dict
del dict[key] if you know the key exists
dict.pop(key) throws error is key does not exist
dict.pop(key, None) return key if it exists. Doesn’t throw error if the key doesn’t exist.
dict.setdefault(key, value)
- returns the value of the item with the specified key
- if the key does not exist, insert the key, with the specified value