gpt4 book ai didi

python - 检查排列是否存在/组合是否唯一

转载 作者:太空宇宙 更新时间:2023-11-03 14:24:58 25 4
gpt4 key购买 nike

我有以下代码,可以创建价格在一定范围内的水果、蔬菜和饮料的组合:

fruits = [('apple', 1), ('banana', 2), ('orange', 3)]
veggies = [('tomato', 1), ('cucumber', 2), ('onion', 3)]
drinks = [('water', 1), ('juice', 2), ('soda', 3)]

for fruit1 in fruits:
for fruit2 in fruits:
for veggie1 in veggies:
for veggie2 in veggies:
for drink1 in drinks:
for drink2 in drinks:
if 12 <= fruit1[1]+fruit2[1]+veggie1[1]+veggie2[1]+drink1[1]+drink2[1] <= 14:
if fruit1 != fruit2:
if veggie1 != veggie2:
if drink1 != drink2:
combos.append((fruit1[0], fruit2[0], veggie1[0], veggie2[0], drink1[0], drink2[0], fruit1[1]+fruit2[1]+veggie1[1]+veggie2[1]+drink1[1]+drink2[1]))

它会检查以确保它不会两次采摘相同的水果/蔬菜/饮料,但我需要确保这些组合是唯一的。

例如,如果我最终得到

('apple', 'banana', 'tomato', 'cucumber', 'water', 'soda', 10) 

我也不想

('banana', 'apple', 'tomato', 'cucumber', 'water', 'soda', 10)

等等。这给我带来了更多的麻烦,因此我们将不胜感激。

最佳答案

你可以这样处理数据

prices = {k:v for items in [fruits, veggies, drinks] for k, v in items}
fru,veg,dri=[i[0] for i in fruits],[i[0] for i in veggies],[i[0] for i in drinks]

from itertools import combinations, product, chain
for items in product(*(combinations(i, r = 2) for i in (fru, veg, dri))):
total = sum(prices[i] for item in items for i in item)
if 12 <= total <= 14:
print tuple(chain.from_iterable(items)) + (total,)

输出

('apple', 'banana', 'tomato', 'onion', 'juice', 'soda', 12)
('apple', 'banana', 'cucumber', 'onion', 'water', 'soda', 12)
('apple', 'banana', 'cucumber', 'onion', 'juice', 'soda', 13)
('apple', 'orange', 'tomato', 'cucumber', 'juice', 'soda', 12)
('apple', 'orange', 'tomato', 'onion', 'water', 'soda', 12)
('apple', 'orange', 'tomato', 'onion', 'juice', 'soda', 13)
('apple', 'orange', 'cucumber', 'onion', 'water', 'juice', 12)
('apple', 'orange', 'cucumber', 'onion', 'water', 'soda', 13)
('apple', 'orange', 'cucumber', 'onion', 'juice', 'soda', 14)
('banana', 'orange', 'tomato', 'cucumber', 'water', 'soda', 12)
('banana', 'orange', 'tomato', 'cucumber', 'juice', 'soda', 13)
('banana', 'orange', 'tomato', 'onion', 'water', 'juice', 12)
('banana', 'orange', 'tomato', 'onion', 'water', 'soda', 13)
('banana', 'orange', 'tomato', 'onion', 'juice', 'soda', 14)
('banana', 'orange', 'cucumber', 'onion', 'water', 'juice', 13)
('banana', 'orange', 'cucumber', 'onion', 'water', 'soda', 14)

如果您只想在 drinks 中选择一个元素,那么您可以像这样更改组合部分

d = {0: 2, 1: 2, 2: 1}
for items in product(*(combinations(j, r=d.get(i)) for i, j in enumerate((fru,veg,dri)))):

随着这个改变,输出变成了

('apple', 'orange', 'cucumber', 'onion', 'soda', 12)
('banana', 'orange', 'tomato', 'onion', 'soda', 12)
('banana', 'orange', 'cucumber', 'onion', 'juice', 12)
('banana', 'orange', 'cucumber', 'onion', 'soda', 13)

关于python - 检查排列是否存在/组合是否唯一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22004463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com