Leetcode Tips n Tricks Flashcards
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’]
~~~
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 could you represent a letter as an integer?
Use ord(letter)
, which will return the unicode integer for that letter
Create a list of 3 zeroes
zeroes = [0] * 3
How do you iterate backwards on a list?
for i in reversed(a):
Explain why my_l_of_l = [[]] * 10
will NOT work in making a list of empty lists?
Because this will only make a list of the same list object!
How do you make a list of empty lists?
my_l_of_l = [[] for _ in range(n)]
If you weren’t allowed to use collections.Counter
to create a counting dictionary, how would you do it?
my_list = [1, 2, 2, 2, 3, 3] count_dict = {} for val in my_list: count_dict[val] = 1 + count_dict.get(val, 0)