Python Flashcards

(13 cards)

1
Q

What is a dictionary in Python and how does it work? How do you access values in a dict? How do you set values in a dict? How do you conditionally get a value in a dict without breaking it?

A

A dictionary (dict) is like an object in JavaScript. It’s defined the same way. For example:

count = {}

This sort of object is a bit different though because its largely like a map. A JavaScript object “coerces” any key to a string whereas the key in a dictionary can be any value. So the boolean “true” could map to a string.

To access or set a value, you use a bracket, so:

count[key] is equal to the value.

You can also set values this way so:

count[key] = 1

If you don’t know if the key/value pair has been set, you can use the get method to return it or return another value if its not there:

count.get(key, 0)

This returns the value associated with key or 0 if it doesn’t exist. Here is an example of setting a value in a dict to +1 of the current even if it doesn’t already exist:

count[key] = count.get(key, 0) + 1

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

How do you make a set in python? How do you add to a set? How do you tell if a value is in a set?

A

mySet = set()

mySet.add(value)

if value in mySet:
return True

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

How do you loop through an array with both the values in the array and the index we’re at?

A

for i, num in enumerate(nums):

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

How do you create a character count array for lowercase letters? Why is this better than using a map to count the elements?

When would you use a map instead of this, and what’s a shortcut?

A

for s in strs:
count = [0] * 26
for c in s:
count[ord(c) - ord(‘a’)] += 1

Note: ord() returns the unicode number, so if we subtract ord(‘a’) we get the correct index of letter in the alphabet for our 26 length array.

If the elements we’re counting aren’t lowercase letters, we need to count using a dictionary:

from collections import defaultdict

for el in elements:
count = defaultdict(int)
for c in el:
count[c] += 1

There is a library that helps us do this quicker:

from collections import Counter

for s in strs:
count = Counter(s)

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

How do you turn a dictionary that holds the count of elements in a string or other array into a key that can be used in a map?

A

key = tuple(sorted(count.items()))

You have to sort the items because if they aren’t sorted, the tuple will produce some different hashable value.

You have to convert to a tuple because the dict is not hashable by default.

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

What’s the benefit of importing defaultdict?

A

Using a normal dict, you have to use checks to make sure the key exists in the dictionary first. For incrementing a value to a key for example in an int dict, you’d have to do:

count[key] = count.get(key, 0) + 1

This returns 0 if the count.get(key) doesn’t already exist. With a default dict, this is done for you, so you can use:

count[key] += 1 instead for an int dict.

You can assume there is a valid value for any key whether it exists or not with this.

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

What are all the default values returned by default dicts?

A

| defaultdict type | Example | Default value |

defaultdict type | Example | Default value |
| —————— | ——————– | ———————– |
| list | defaultdict(list) | [] (empty list) |
| set | defaultdict(set) | set() (empty set) |
| int | defaultdict(int) | 0 |
| float | defaultdict(float) | 0.0 |
| str | defaultdict(str) | '' (empty string) |
| dict | defaultdict(dict) | {} (empty dictionary) |
| bool | defaultdict(bool) | False |

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

If a dictionary holds keys that point to lists, how would you extract the lists and put them into a new list?

A

list(groups.values())

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

How do you import a library from Python?

A

from collections import Counter

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

If you need to iterate over a map and access both key and value pairs, how do you do that?

A

for k, v in count.items():
freq[v].append(k)

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

Explain how a list comprehension works in python. Give an example where you use the variable and one where you don’t. Also give an example where you use an optional 4th value in the comprehension and what its for.

A

A list comprehension allows us to make a new list out of an existing iterable.

There are 3 values you define in a list comprehension (and a 4th optional value):

Expression, variable, iterable (and condition)

[ expression(variable) for variable in iterable if condition ]

Here is an example where you don’t use the variable:

freq = [[] for _ in range(len(nums) + 1)]

In this bucket sort example, we want to create a list of lists as long as the nums array (plus one because its a frequency count, and no values will be in frequency ‘zero’)

In this example, we are only concerned with the size of the nums array and don’t care about the actual values within the nums array to produce the new list. That’s why we use the underscore, because no variable is used in the expression.

Here is an example where we do use the variable and condition:

squares_of_even = [x**2 for x in range(5) if x % 2 == 0]

This iterates over “range(5)”, and since the expression needs the variables at each index of range(5), we define it in the variable slot.

This also uses a condition, which is used as a filter. We’re not concerned with odd numbers, so we only add values to the new list if the remainder of 2 is equal to zero (even numbers only).

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

How does range() work in python? What are all 3 possibilities with parameters within the function? What is something cool you can do with the third parameter?

A

range() returns numbers in a particular range you define. This is a special iterable object because it isn’t a list. It returns each number one at a time so it doesn’t take up any memory. This is efficient even for huge ranges.

Example one:

range(stop)
This returns numbers from 0 up to stop-1
range(5) → 0,1,2,3,4

Example two:

range(start, stop)
Returns numbers from start up to stop-1
range(2, 6) → 2,3,4,5

Example three:

range(start, stop, step)
Returns numbers from start to stop-1 with step
range(1, 10, 2) → 1,3,5,7,9

This third example is cool because with step, you can define a negative number to count backwards. For example, with the bucket sort method of the top k frequent elements problem, you need to iterate through the frequency list backwards to get the most frequent elements. You do it like this:

    res = []
    for i in range(len(freq) - 1, 0, -1):
        for num in freq[i]:
            res.append(num)
            if len(res) == k:
                return res

This starts at the end of the frequency list and iterates backwards through the list an index at a time until we hit the first element.

In this example, zero works as the stop element because no variables will be within the ‘zero’ index as that would mean none of those variables existed in the first place. If we needed to access the zero index, we would need that to be -1.

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