I am writing a function that returns a list of car models. The input is a string of comma separated cars. Duplicate entries are not added to the result. The elements in the list should be in the same order as they appear in the input string. If the input string is empty, the result is an empty list. I modified it to support multiple model names, e.g. print(car_models("Tesla Model S,Skoda Super Lux Sport))
gives ['Model S', 'Super Lux Sport']
.
def car_models(all_cars: str) -> list:
if not all_cars:
return []
all_models = []
cars = all_cars.split(",")
for car in cars:
unique_car = car.split(" ")
if unique_car[1] not in all_models:
all_models.append(" ".join(unique_car[1:]))
return all_models
While testing the code, an error occurred:
And I can't figure out what's wrong, can anyone tell me how to fix it?
CodePudding user response:
Since you're appending " ".join(unique_car[1:])
to the list, you need to use the same thing when checking if already exists.
Solve this easily by assigning that to a variable, so you can use the same thing in the in
test and append()
call.
def car_models(all_cars: str) -> list:
if not all_cars:
return []
all_models = []
cars = all_cars.split(",")
for car in cars:
car_words = car.split(" ")
model = " ".join(car_words[1:])
if model not in all_models:
all_models.append(model)
return all_models
CodePudding user response:
Checking for the existence of some object in a list will not perform optimally when the list is very large. Better to use a set.
Here are two versions. One without a set and the other with:
def car_models(all_cars):
result = []
for car in all_cars.split(','):
if (full_model := ' '.join(car.split()[1:])) not in result:
result.append(full_model)
return result
def car_models(all_cars):
result = []
resultset = set()
for car in all_cars.split(','):
if (full_model := ' '.join(car.split()[1:])) not in resultset:
result.append(full_model)
resultset.add(full_model)
return result
Note:
If order didn't matter (it does in this case) one could just use a set
CodePudding user response:
First, I suppose you misspelled the command and should be like:
print(car_models("Tesla Model S","Skoda Super Lux Sport"))
And then, instead of:
unique_car = car.split(" ")
I should use something like:
unique_car = car[car.find(" ") 1:]
to have full name of the model compared. Even with:unique_brand = car[:car.find(" ")]
you can be able to create a beautiful dictionary like: {'brand1':[model1, model2], 'brand2':...}
Besides, if the problem is coming from the test, please share your test code.