1. Snake Case
Solution Path 1: Build each word in a separate variable
def make_snake_case(camel_case):
res = ""
cur_word = ""
for ch in camel_case:
if ch.isupper():
res += f"{cur_word}_"
cur_word = ch.lower()
else:
cur_word += ch
res += cur_word
return res
Solution Path 2: Go through full input and convert uppercase characters to underbar + lowercase
def make_snake_case(camel_case):
res = ""
for ch in camel_case:
if ch.isupper():
res += f"_{ch.lower()}"
else:
res += ch
return res
2. Merge Index
def merge_index(index, file_titles):
result = {}
for term in index:
result[term] = {}
for doc in index[term]:
result[term][doc] = file_titles[doc]
return result
3. Most Popular Document
def most_popular_document(index):
document_count = {}
for term in index:
for doc in index[term]:
if doc not in document_count:
document_count[doc] = 0
document_count[doc] += 1
most_popular = ""
most_popular_count = 0
for document in document_count:
if document_count[document] > most_popular_count:
most_popular = document
most_popular_count = document_count[document]
return most_popular
4. Sorting
Given the following lists, provide the output of each code snippet:
foo = [-1, 5, 3, 9, 2, 0]
bar = sorted(foo)
baz = sorted(foo, reverse=True)
a.
[2, 3, 5, 9]
b.
[0, 2, 3]
c.
[2, 0, -1]
d.
[0, -1]
5. Air Travel
def can_reach(filename, start, end):
with open(filename, "r") as f:
data = json.load(f)
# Flights that are nonstop from the start location
# (i.e. airports you can reach directly from `start`)
flights = data[start]["flights"]
for first_flight in flights:
code = first_flight["airport_code"]
if code == end:
return True
# Flights that are within one stop from the start location
# (i.e. airports you can reach from any of the `first_flight`
# airport codes)
within_one_stop = data[code]["flights"]
for second_flight in within_one_stop:
if second_flight["airport_code"] == end:
return True
return False
6. Timing
a. Class Implementation
class Clock:
def __init__(self, hour, minute):
self.hour = hour
self.minute = minute
def get_hour(self):
return self.hour
def get_minute(self):
return self.minute
b. Get Time in Minutes
def get_time_in_minutes(self):
hour_converted = self.hour * 60
return hour_converted + self.minute
c. Minutes Between
return time2.get_time_in_minutes() - time1.get_time_in_minutes()