如何在Python中找到满足条件(最大和最小阈值)的所有可能组合?
给定 和阈值如何在Python中找到满足条件(最大和最小阈值)的所有可能组合?,python,Python,给定 和阈值 names = ["bread","peanut_butter","yogurt","coffe"] calories = [150,400,100,75] 我想得到所有可能的食物组合,例如: max_calories = 500 min_calories = 250 这就是我到目前为止得到的。我通过def greedy只获得了“花生酱=400”和“面包+酸奶+咖啡=350”通过def gready2。但我不知道如何通过def gready2获得所有剩余的组合 bread +
names = ["bread","peanut_butter","yogurt","coffe"]
calories = [150,400,100,75]
我想得到所有可能的食物组合,例如:
max_calories = 500
min_calories = 250
这就是我到目前为止得到的。我通过def greedy
只获得了“花生酱=400”
和“面包+酸奶+咖啡=350”
通过def gready2
。但我不知道如何通过def gready2
获得所有剩余的组合
bread + yogurt = 250
bread + yogurt + coffe = 350
peanut_butter + yogurt = 500
peanut_butter + coffe = 475
peanut_butter = 400
类食品(对象):
定义初始值(self,n,c):
self.name=n
自身热量=c
def获取热量(自身):
返回自己的卡路里
定义(自我):
返回f“{self.name}:<{self.carries}>”
def构建菜单(名称、卡路里):
“”“相同长度的名称、卡路里列表。
列出一个字符串列表
卡路里数列
返回食物列表“
菜单=[]
对于范围内的i(len(卡路里)):
菜单.附加(食物(名称[i],卡路里[i]))
返回菜单
def贪婪(项目、最大成本、最小成本):
#假设项目是一个列表
项目透视=项目
结果=[]
总成本=0.0
对于范围内的i(len(itemsCopy)):
如果(ItemScope[i].GetCarries())=minCost:
结果.追加(项目透视[i])
totalCost+=ItemScope[i].GetCarries()
返回(结果、总成本)
def GREDY2(项目、最大成本、最小成本):
#假设项目是一个列表
项目透视=项目
结果=[]
总成本=0.0
对于范围内的i(len(itemsCopy)):
如果(totalCost+ItemScope[i].GetCarries())
------------------------------------
所取项目的总价值=325.0
面包:<150>
酸奶:<100>
咖啡:<75>
这里的问题
这里的问题是,您并没有真正解析所有可能的成分组合。
你只是试图添加更多的成分,直到你达到允许的最大量或热量,但这将导致许多可能性,仍然没有探索
要生成所有长度的所有组合,我喜欢使用itertools
包:
来自itertools导入组合,链
名称=[“面包”、“花生酱”、“酸奶”、“咖啡”]
所有组合=链(*(组合(名称,i)表示范围内的i(len(名称)+1)))
对于所有组合中的组合:
打印(组合)
你当然可以从这里算出你的代码。请注意,这是对所有组合的详尽解析,可以有更高效的算法来最终实现您想要的
完整代码示例
为了完整起见,我提供了完整的Python代码,您可以使用这些代码来查找所需的组合:
来自itertools导入组合,链
#投入
名称=[“面包”、“花生酱”、“酸奶”、“咖啡”]
卡路里=[15040010075]
最大热量=500
最低热量=250
#构建从名称到卡路里数量的映射
namesToCalories={key:key的值,zip中的值(名称,卡路里)}
结果=[]
#解析所有组合
所有组合=链(*(组合(名称,i)表示范围内的i(len(名称)+1)))
对于所有组合中的组合:
#为这个组合获取卡路里
该组合的卡路里=总和(组合中名称的名称为“名称”)
#最小/最大值的测试
如果此组合的热量>最小热量,而此组合的热量<最大热量:
结果+=[combi]
打印(结果)
我添加了一个代码示例来演示组合的解析。请编辑您的答案以显示更新的代码,或者就代码中的特定错误询问其他问题!谢谢,我将编辑我的帖子。我正在测试您刚刚发布的新代码感谢您的帮助@Corentin,我学到了很多。我意识到函数chain(*(范围(len(name))中I的组合(name,I))
不会生成完整的组合(“面包”、“花生酱”、“酸奶”、“咖啡”)。应该是这样吗?
class Food(object):
def __init__(self, n, c):
self.name = n
self.calories = c
def getCalories(self):
return self.calories
def __str__(self):
return f"{self.name}: < {self.calories} >"
def buildMenu(names, calories):
"""names, calories lists of same length.
name a list of strings
calories lists of numbers
returns list of Foods"""
menu = []
for i in range(len(calories)):
menu.append(Food(names[i], calories[i]))
return menu
def greedy(items, maxCost, minCost):
#Assumes items a list
itemsCopy = items
result = []
totalCost = 0.0
for i in range(len(itemsCopy)):
if (itemsCopy[i].getCalories()) <= maxCost:
if (itemsCopy[i].getCalories()) >= minCost:
result.append(itemsCopy[i])
totalCost += itemsCopy[i].getCalories()
return (result, totalCost)
def greedy2(items, maxCost, minCost):
#Assumes items a list
itemsCopy = items
result = []
totalCost = 0.0
for i in range(len(itemsCopy)):
if (totalCost+itemsCopy[i].getCalories()) <= maxCost:
result.append(itemsCopy[i])
totalCost += itemsCopy[i].getCalories()
return (result, totalCost)
def testGreedy(items, constraint, constraint2):
taken, val = greedy(items, constraint, constraint2)
for item in taken:
print(' ', item)
print(" ------------------------------------")
def testGreedy2(items, constraint, constraint2):
taken2, val2 = greedy2(items, constraint, constraint2)
print(" Total value of items taken =", val2 )
for item in taken2:
print(" ", item)
def testGreedys(foods, maxUnits, minUnits):
print('Allocating', maxUnits,
'calories:')
print("")
testGreedy(foods, maxUnits, minUnits)
testGreedy2(foods, maxUnits, minUnits)
names = ["bread","peanut_butter","yogurt","coffe"]
calories = [150,400,100,75]
foods = buildMenu(names, calories)
testGreedys(foods, 500, 250)
Allocating 500 calories:
peanut_butter: < 400 >
------------------------------------
Total value of items taken = 325.0
bread: < 150 >
yogurt: < 100 >
coffe: < 75 >