如何通过汇总键的值直到其达到50,然后将这些键写入文件来遍历字典。
例如:
fruits={'mangoes':10,'banana':20,'orange':20,'grapes':40,'apple':10,'strawberry':20,'cherry':30}
输出应该是多袋,每批最多有50个水果。
在此示例中:
bag1:
mangoes,
banana,
orange
bag2:
grapes,
apple
bag3:
strawberry,
cherry
答案 0 :(得分:1)
如果您只希望按字典顺序排列,则可以执行以下操作:
def bags(fruits, max_size):
bag = []
current_size = 0
for name, count in fruits.items():
if count + current_size > max_size:
yield bag
bag = []
current_size = 0
bag.append(name)
current_size += count
if bag:
yield bag
for bag in bags(fruits, 50):
print bag
答案 1 :(得分:0)
所以我只是写了一些可以递归地跟踪元素和当前总和的东西。我认为它将为每个子选项提供每个选项。然后,它仅使用生成器项目构建袋子。 (Python 3,用于yeild from
)
def subset_sum(fruits, target, partial=[], partial_sum=0):
if partial_sum == target:
yield partial
if partial_sum >= target:
return
for i, n in enumerate(fruits):
remaining = fruits[i + 1:]
yield from subset_sum(remaining, target, partial + [n], partial_sum + n[1])
if __name__ == "__main__":
fruits={'mangoes':10,'banana':20,'orange':10,'grapes':40,'apple':10,'strawberry':20,'cherry':30}
fruits=tuple((k,v) for k,v in fruits.items())
result = subset_sum(fruits,50)
for i, n in enumerate(result):
print('Bag {}: {}'.format(i, ' '.join([f[0] for f in n])))
Bag 0: mangoes banana orange apple
Bag 1: mangoes banana strawberry
Bag 2: mangoes orange apple strawberry
Bag 3: mangoes orange cherry
Bag 4: mangoes grapes
Bag 5: mangoes apple cherry
Bag 6: banana orange strawberry
Bag 7: banana apple strawberry
Bag 8: banana cherry
Bag 9: orange grapes
Bag 10: orange apple cherry
Bag 11: grapes apple
Bag 12: strawberry cherry