Python Flashcards

1
Q

Strings mutable?

A

No, immutable. If you want to concat a bunch of strings without creating a new string for each intermediate operation, use ““.join(list)

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

Returns true if all char are alphanumeric (and at least one char)

A

isalnum()

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

Returns true if all char are letters (and at least one char)

A

isalpha()

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

Returns true if all char are digits (and at least one digit)

A

isdigit()

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

Returns a string which is a concatenation of the strings in a list (or other iterable)

A

join
““.join

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

Split a string on whitespace, ignore empty strings

A

split no param
That means splitting an empty string will return an empty list

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

Split a string on whitespace, include empty string

A

split(‘ ‘)

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

Remove leading and trailing whitespace

A

strip

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

Add an element to list

A

append
If you’re trying to create a list of lists, use append rather than +=

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

Combine two lists

A

+ 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

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

set operations

A

set()
add, remove

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

list pop no argument

A

removes the last item in the list

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

get k,v from map

A

items()
Returns a dict_items object which is not accessible via index.
Need to use operator.getitem()

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

sort

A

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

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

convert comparator to key

A

func_tools.cmp_to_key

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

sorted

A

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)

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

class defn

A

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

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

return the key corresponding to the max val in a freq map

A

max(freq_map.items(), key=operator.itemgetter(1))[0]

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

f = operator.itemgetter(2)
what does f(‘ABC’) return

A

Returns C, the item at index 2

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

g = operator.itemgetter(2, 5, 3)
what does g(‘ABCDEF’) return?

A

Returns a list with the items at indicies 2, 5, and 3
(‘C’, ‘F’, ‘D’)

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

initialize dict

A

defaultdict(int)

22
Q

remove first element of list

A

list.pop(0)
O(n)!
Use deque instead

23
Q

reverse a list

A

list[::-1]
list.reverse() does it in place. can’t assign a return value.
list.reversed() returns a new reversed list.

24
Q

pop vs get for map

A

pop will throw a KeyError is no default is provided and the key is not found

25
max int
MAX SIZE from sys import maxsize sys.maxsize or sys.maxsize - 1
26
sort ascending
list.sort() In place
27
l1.extend(l2)
Adds the second list to the first list in place. Returns None. Need to return l1 for the combined list.
28
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()
29
Initialize array fixed value
dp = [None] * n dp = [float('inf')] * n dp = [float('-inf')] * n
30
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.
31
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)
32
import types such as List
from typing import List
33
are collections hashable? can they be used as a key in hashmaps?
No. Use tuple instead.
34
create list from dict_values
list(dict_values)
35
create defaultdict
from collections import defaultdict defaultdict(int) defaultdict(float) defaultdict(str) defaultdict(list) can do other fancier things like a lambda function
36
call class
s = Solution() s.method()
37
import Counter
from collections import Counter
38
pass func to sort
list.sort(lambda x: x[0])
39
Combine a list of lists
Use + instead of append!
40
Sort descending
list.sort(reverse=True)
41
How many unicode characters are there?
More than a million
42
how do you convert the right-most bit to zero?
AND n & n-1
43
Binary Search Time Complexity
O(log n) Collection must be ordered
44
divmod
divmod(n, 3) returns (result of division by 3, remainder)
45
heap operations
Import heapq heap = [] Heapq.heapify(heap) Heapq.heappush(h, value) Heapq.heappop(h) while heap nlargest nsmallest
46
heap[0]
smallest value python heap implementation is min heap
47
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 [
48
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.
49
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
50
51