【发布时间】:2019-09-09 22:43:03
【问题描述】:
我需要通过将值列表 l 加/减到 n 来计算从值 n 达到值 x 的最小方法数。
例如:值 n = 100,值 X = 45 列表, l,: 50,6,1
最好的方法是说: 100-50-6+1 = 45
我想要一个程序来解决给定列表 l 的任何 x 和 n 值
我真的很难概述我将如何写这个。
我对如何克服以下问题感到困惑:
- 如果我应该尝试添加或 减法以及应该执行多少次。例如我 可能需要先减法,然后加法,再减法以达到 解决方案
- 如何包含足够的 for/while 循环以确保我可以提供 所有可能输入值的解决方案
以前有没有人遇到过这样的问题,并且知道如何为这种解决方案概述代码(如果它有助于指导我了解可以帮助我的特定可用功能,我正在使用 Python)
谢谢
这是我目前的尝试,但我被卡住了
inputA = ""
while inputA == "":
inputA = input("""Please enter two numbers, separated by a comma.
The first value should indicate the number of jugs:
The second value should indicate the volume to be measured
""")
itemList = list(inputA.split(","))
valueToMeasure = int(itemList[1])
inputB = ""
while inputB == "":
inputB = input("Plese enter the volumes for the {} jug(s) listed: ".format((itemList[0])))
if len(inputB.split(",")) != int(itemList[0]):
inputB = ""
TargetVolume = itemList[1]
jugSizes = inputB.split(",")
print("Calculating: smallest number of steps to get", TargetVolume, "ml using jugs of sizes:", jugSizes)
jugSizes.sort()
jugSizes.reverse()
largestJug = int(jugSizes[0])
ratioTable = {}
for item in jugSizes:
firstVal = int(jugSizes[0])
itemV = int(item)
valueToAssign = firstVal/itemV
ratioTable[int(item)] = int(valueToAssign)
taskPossible = True
if valueToMeasure > largestJug:
print ("Impossible task")
taskPossible = False
newList = jugSizes
if taskPossible == True:
for item in jugSizes:
if item < TargetVolume: break
newList = newList[1:]
newDict = {}
for itemA in ratioTable:
if int(itemA) < int(item):
newDict[itemA]= ratioTable[itemA]
print ("Do work with these numbers:", newDict)
【问题讨论】:
-
你有没有尝试过?展示你的努力
-
尝试使用递归算法。
-
听起来您应该为
I上的数学运算符创建所有排列的列表,然后查看其中哪些等同于X -
您是否从列表中取样,是否更换?
-
@JanChristophTerasa 我缩短了列表,正如您在每个循环结束时看到的那样