forked from exercism/python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
52 lines (39 loc) · 1.4 KB
/
example.py
File metadata and controls
52 lines (39 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from functools import reduce
BASE_COST = 800
discount = [1.0, 1.0, 0.95, 0.9, 0.8, 0.75]
def group_cost(group):
return len(group) * discount[len(group)]
class Grouping:
def __init__(self, groups=None):
self.groups = [set()] if groups is None else groups
def total(self):
return sum(map(group_cost, self.groups)) * BASE_COST
def dup(self):
return Grouping(list(map(set, self.groups)))
def add_to_valid(self, book):
"""Returns all possible groupings from the
current grouping adding book
"""
other = self.dup()
other.groups.sort(key=lambda g: len(g))
results = []
for index, group in enumerate(other.groups):
if book not in group:
other2 = other.dup()
other2.groups[index].add(book)
results.append(other2)
if not results:
other.groups.append(set([book]))
return [other]
return results
def __lt__(self, other):
return self.total() < other.total()
def step(basket, book):
return [group for groupings in basket
for group in groupings.add_to_valid(book)]
def total(basket):
if len(basket) == 0:
return 0
basket = sorted(basket)
start = Grouping([{basket[0]}])
return round(min(reduce(step, basket[1:], [start])).total())