Function that returns a list of cars

Question:

As part of my homework it is required to write a function that returns a list of cars, i.e. the function searches for cars where the search string is one of the car models and the search is case insensitive.

def search_by_model(all_cars: str, model: str) -> list:
    if not all_cars or not model:
        return []
    all_makes = []
    cars = all_cars.split(",")
    for car in cars:
        unique_car = car.split(" ")
        if model.lower() == unique_car[1].lower():
            all_makes.append(" ".join(unique_car[0:]))
    return all_makes

So, in my case print(search_by_model("Audi A4,Audi a4 2021,Audi A40", "A4")) yields ['Audi A4', 'Audi a4 2021'], which is OK. However, I don’t understand how to do the same but with two or more words, for example, if I want the "a4 2021" model, then I should only get "Audi a4 2021".

Task description:
enter image description here

Asked By: Cornifer

||

Answers:

You just need to check that all the words in model are in unique_car:

def search_by_model(all_cars: str, model: str) -> list:
    if not all_cars or not model:
        return []
    all_makes = []
    cars = all_cars.split(",")
    model = model.lower().split(" ")
    for car in cars:
        unique_car = car.split(" ")
        if all(mdl in map(str.lower, unique_car) for mdl in model):
            all_makes.append(" ".join(unique_car))
    return all_makes

print(search_by_model("Audi A4,Audi a4 2021,Audi A40", "A4"))
# ['Audi A4', 'Audi a4 2021']
print(search_by_model("Audi A4,Audi a4 2021,Audi A40", "A4 2021"))
# ['Audi a4 2021']
Answered By: Nick
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.