Leetcode Tips n Tricks Flashcards

1
Q

What’s a cleaner way of writing the code below?
~~~
my_dict = {}
if value in my_dict:
my_dict[value].append(‘hi’)
else:
my_dict[value] = [‘hi’]
~~~

A
from collections import defaultdict
my_dict = defaultdict(list)
my_dict[value].append('hi')

defaultdict will return the default value instead of returning a KeyError

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

How could you represent a letter as an integer?

A

Use ord(letter), which will return the unicode integer for that letter

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

Create a list of 3 zeroes

A

zeroes = [0] * 3

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

How do you iterate backwards on a list?

A

for i in reversed(a):

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

Explain why my_l_of_l = [[]] * 10 will NOT work in making a list of empty lists?

A

Because this will only make a list of the same list object!

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

How do you make a list of empty lists?

A

my_l_of_l = [[] for _ in range(n)]

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

If you weren’t allowed to use collections.Counter to create a counting dictionary, how would you do it?

A
my_list = [1, 2, 2, 2, 3, 3]
count_dict = {}
for val in my_list:
    count_dict[val] = 1 + count_dict.get(val, 0)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly