question 146 Advanced Functions & Recursion · medium
Split a list by any rule
Several reports need the same job: split a list in two, the items that pass some rule and the items that don't. Write a reusable partition(items, test), where test is a function that takes one item. Then write split_orders(orders, minimum), which uses partition with an inline lambda to split orders into those whose total is at least minimum and the rest, returning their order IDs.
Function 1
partition(items, test) → a tuple (passed, failed) of two new lists, each in the original order; an item passes when test(item) is trueFunction 2
split_orders(orders, minimum) → (large_ids, small_ids), using partitionordersa list of dictionaries with
order_id and totalRules
items is not changed; a rule may return any value, which counts by its truthiness (so "" fails)Examples
callsplit_orders([{'order_id': 'O100282', 'total': 35.84}, {'order_id': 'O100376', 'total': 91.47}, {'order_id': 'O100918', 'total': 55.72}, {'order_id': 'O101219', 'total': 246.6}], 60)returns(['O100376', 'O101219'], ['O100282', 'O100918'])
callsplit_orders([{'order_id': 'O100282', 'total': 35.84}, {'order_id': 'O100376', 'total': 91.47}, {'order_id': 'O100918', 'total': 55.72}, {'order_id': 'O101219', 'total': 246.6}], 300)returns([], ['O100282', 'O100376', 'O100918', 'O101219'])
callsplit_orders([{'order_id': 'O100282', 'total': 35.84}, {'order_id': 'O100376', 'total': 91.47}, {'order_id': 'O100918', 'total': 55.72}, {'order_id': 'O101219', 'total': 246.6}], 0)returns(['O100282', 'O100376', 'O100918', 'O101219'], [])