Code mostly works except the second answer problem with quotes in list
Question:
def car_makes(all_cars: str) -> list:
lst = all_cars.split(",")
car_brands = []
for i in lst:
brand = i.split(" ")
car_brands.append(brand[0])
firms = list(dict.fromkeys(car_brands))
return firms
if __name__ == '__main__':
print(car_makes("Audi A4,Skoda Super,Skoda Octavia,BMW 530,Seat Leon,Skoda Superb,Skoda Superb,BMW x5"))
print(car_makes(""))
# expected answers
# ['Audi', 'Skoda', 'BMW', 'Seat']
# []
Code mostly works except the second answer has to stay empty but I get ['']
. What am I missing here?
Answers:
From the str.split
documentation:
Splitting an empty string with a specified separator returns ['']
.
You could check whether the given string is empty and return an empty list in that case:
def car_makes(all_cars: str) -> list:
if all_cars == "":
return []
lst = all_cars.split(",")
# ...
return firms
def car_makes(all_cars: str) -> list:
lst = all_cars.split(",")
car_brands = []
for i in lst:
brand = i.split(" ")
car_brands.append(brand[0])
firms = list(dict.fromkeys(car_brands))
return firms
if __name__ == '__main__':
print(car_makes("Audi A4,Skoda Super,Skoda Octavia,BMW 530,Seat Leon,Skoda Superb,Skoda Superb,BMW x5"))
print(car_makes(""))
# expected answers
# ['Audi', 'Skoda', 'BMW', 'Seat']
# []
Code mostly works except the second answer has to stay empty but I get ['']
. What am I missing here?
From the str.split
documentation:
Splitting an empty string with a specified separator returns
['']
.
You could check whether the given string is empty and return an empty list in that case:
def car_makes(all_cars: str) -> list:
if all_cars == "":
return []
lst = all_cars.split(",")
# ...
return firms