回答編集履歴

1

edit

2019/06/20 14:00

投稿

mkgrei
mkgrei

スコア8560

test CHANGED
@@ -1 +1,75 @@
1
1
  前から選んで、入れることができたら受け入れるという特に探索をしていないコードだからではないですか?
2
+
3
+
4
+
5
+ 総当たり:
6
+
7
+ https://wandbox.org/permlink/8ug63FVQMO8Ef815
8
+
9
+
10
+
11
+ ```python
12
+
13
+ class Item:
14
+
15
+ def __init__(self,name,weight):#クラスの定義
16
+
17
+ self.name=name
18
+
19
+ self.weight=weight
20
+
21
+
22
+
23
+ #初期化する
24
+
25
+ limit = 15
26
+
27
+ items=[Item("A",7),Item("B",4),Item("C",5),Item("D",6),Item("E",3)]
28
+
29
+ L=len(items)
30
+
31
+
32
+
33
+ import itertools
34
+
35
+
36
+
37
+ def calc_total_weight(items, choices, limit=15):
38
+
39
+ ret = sum([x.weight*a for x, a in zip(items, choices)])
40
+
41
+ if ret > limit:
42
+
43
+ return 0
44
+
45
+ return ret
46
+
47
+
48
+
49
+ choices_weight = [(choices, calc_total_weight(items, choices, limit=limit))
50
+
51
+ for choices in itertools.product([0, 1], repeat=L)]
52
+
53
+ ans = list(sorted(choices_weight, key=lambda x: x[1], reverse=True))
54
+
55
+
56
+
57
+ print('選んだ荷物の組み合わせの重みは')
58
+
59
+ print(ans[0][1])
60
+
61
+ best_weight = ans[0][1]
62
+
63
+ for v in ans:
64
+
65
+ if v[1] < best_weight:
66
+
67
+ break
68
+
69
+ print('選んだ荷物の組み合わせは')
70
+
71
+ print(v[0])
72
+
73
+ print([items[i].name for i, v in enumerate(v[0]) if v == 1])
74
+
75
+ ```