【发布时间】:2020-02-20 12:01:31
【问题描述】:
我遇到了以下问题,我的代码已经变得一团糟,我陷入了困境。
您可以在一些商店消费(大约 15 美元,只是一些正整数) 您只能在两种情况下使用这笔钱:
1) 您从每家商店只购买一件商品。
2) 你花光了所有的钱(没有剩余,也没有债务)
找出所有可能的方式来满足上述要求。
实际上,您获得了一个预算 int 和一些类似
的数组9 和 [[1,2,3],[0,5],[2,3,8]]
其中每个内部数组列出了商店中商品的价格。可以有任意多的商店,有任意多的物品。成本不能是负数,但它们可以是免费的!
这里的预期解决方案是:
[[1,5,3],[2,5,2],[1,0,8]]
由于每个数组包含来自每个商店的一个项目,每个总计 9 个,并且存在所有可能性。 只是为了让它更难,速度是最重要的。
以下是我的代码已经陷入疯狂并且几乎完全缺乏功能:
def Stepper(bud,LOL):
n=len(LOL)
lasts=[]
indices=[0 for j in range(n)]
focus=0
funds=[0 for j in range(n+1)]
funds[0]=bud
sols=[]
moveable=[]
for j in range(n):
length=len(LOL[j])
if(length==0):
return []
lasts.append(length-1)
if(moveable==[]):
if(length==1):
funds[j+1]=funds[j]-LOL[j][0]
else:
moveable.append(j)
focus=j
while(moveable!=[]):
while(LOL[focus][indices[focus]] > funds[focus]):
indices[focus]+=1
if(indices[focus]==lasts[focus]):
if(moveable[-1]==focus):
moveable.remove(focus)
if(moveable==[]):
if(focus<n-1):
moveable.append(focus+1)
funds[focus+1]=funds[focus]-LOL[focus][indices[focus]]
#print(n,lasts,indices,focus,moveable,funds,sols)
if((funds[focus+1]!=0) and (focus<n-1)):
focus+=1
indices[focus]=0
else:
if(funds[focus+1]==0):
for j in range(focus+1,n):
indices[j]=lasts[j]
sols.append(list(indices))
if(moveable[-1]==n-1):
moveable.remove(n-1)
if(moveable!=[]):
focus=moveable[-1]
indices[focus]+=1
if(indices[focus]==lasts[focus]):
if(moveable[-1]==focus):
moveable.remove(focus)
if(moveable==[]):
if(focus<n-1):
moveable.append(focus+1)
funds[focus+1]=funds[focus]-LOL[focus][indices[focus]]
focus+=1
indices[focus]=0
return(sols)
bud 是预算,LOL 是列表列表(商店和价格)
【问题讨论】:
-
你好,你需要实现树遍历深度优先算法,从右上角(第一家商店最后价格)到左下角(最后商店第一价格)。通用原则到处都有很好的描述。通过检查当前
balance(所有遍历节点的总和)budget,还可以显着提高性能,因此当它克服时,您只需跳过以下无法通过 itertools.product 获得的深入遍历。跨度>
标签: python arrays optimization