Specification: Find all buyers that ordered every food item at least once.
Example input/output:
Input:
food
id | name |
---|---|
1 | Burrito |
2 | Sushi |
Input:
orders
id | buyer | food |
---|---|---|
1 | Will | 1 |
2 | Scott | 2 |
3 | Scott | 2 |
4 | Will | 2 |
Output:
[Will]
Python - Imperative
def purchased_all_food(food, orders): n_food = len(food) unique_orders = defaultdict(set) for order in orders: unique_orders[order["buyer"]].add(order["food"]) buyers = [] for buyer, orders in unique_orders.items(): if len(orders) == n_food: buyers.append(buyer) return buyers
Python - Functional
def purchased_all_food(food, orders): n_food = len(food) buyers = set([order["buyer"] for order in orders]) return [ buyer for buyer in buyers if len(set([order["food"] for order in orders if order["buyer"] == buyer])) == n_food ]
Python - Pandas
def purchased_all_food(food, orders): n_food = len(food) n_unique_orders = (orders .groupby('buyer') .food.unique() .map(len)) return n_unique_orders[n_unique_orders == n_food].index.values
R - Tidyverse
purchased_all_food <- function(food, orders) { n_food <- count(food) orders %>% group_by(buyer) %>% distinct(food) %>% count() %>% filter(n == n_food) %>% pull(buyer) }
SQL - SQLite
SELECT DISTINCT buyer FROM orders o1 WHERE (SELECT COUNT(DISTINCT food) FROM orders o2 WHERE o1.buyer = o2.buyer) = (SELECT COUNT(*) FROM food)
Datalog - Souffle
.decl has_purchased(Buyer:symbol, Food:number) has_purchased(Buyer, Food) :- orders(Buyer, Food, _). purchased_all_food(Buyer) :- orders(Buyer, _, _), N_food = count : food(_, _), N_unique_orders = count : has_purchased(Buyer, _), N_food = N_unique_orders.
Q - kdb+
buyers: `buyer xgroup orders; total: count food; purchased_all_food: (where {(count distinct x[`food]) = total} each buyers) `buyer