Reputation: 171
I have different product groups, let's say toys, clothes and food. When I get a series (or list) of products I want to know if they all fall in one group or if I have products from a few groups.
Let's make an example:
toys=['Car', 'Teddy Bear', 'Doll']
food=['Banana', 'Cola', 'Bread', 'Milk']
So when I get ['Cola', 'Milk']
I want it to return True (they all fall in food) and when I get ['Milk', 'Banana', 'Car']
I want it to return False (contains products of both toys
AND food
).
Is there a way to check this other than looping trough all my groups and checking one by one if all products are in that specific group?
Thank you!
Upvotes: 2
Views: 65
Reputation: 118
You could use the set data structure in Python.
toys=['Car', 'Teddy Bear', 'Doll']
food=['Banana', 'Cola', 'Bread', 'Milk']
def is_in_one_group(my_list):
belongs_in_group = [set(my_list).issubset(toys), set(my_list).issubset(food)]
return sum(belongs_in_group) == 1
is_in_one_group(['Cola', 'Milk'])
# True
is_in_one_group(['Milk', 'Banana', 'Car'])
# False
is_in_one_group([])
# False
Upvotes: 1
Reputation: 195543
This is essentially a set operation. You can convert the toys
and food
to sets and then use set.intersection
. For example:
toys = ["Car", "Teddy Bear", "Doll"]
food = ["Banana", "Cola", "Bread", "Milk"]
toys, food = set(toys), set(food)
def is_only_one_group(l):
return bool(toys.intersection(l)) + bool(food.intersection(l)) == 1
print(is_only_one_group(["Milk", "Banana", "Car"]))
print(is_only_one_group(["Cola", "Milk"]))
Prints:
False
True
Upvotes: 2
Reputation: 18315
You can build dictionaries out of your lists such that entries of the lists are the keys and values are the name of the list they belong to. Then we can map the items in the new list and check if the number of unique elements is 1 or not:
toys_dict = dict.fromkeys(toys, "toys")
food_dict = dict.fromkeys(food, "food")
combined_dict = {**toys_dict, **food_dict}
def is_only_one_group(new_list):
return len(set(combined_dict[val] for val in new_list)) == 1
using as
>>> is_only_one_group(["Cola", "Milk"])
True
>>> is_only_one_group(["Milk", "Banana", "Car"])
False
Upvotes: 1