我需要通过将值列表l添加/减去n来计算从值n获得值x的最小方式。
例如:值n = 100,值X = 45 列表,l,:50,6,1
做到这一点的最好方法是说: 100-50-6 + 1 = 45
我想要一个程序针对x和n给定列表l中的任何值进行计算
我真的很努力地概述如何写这篇文章。
我对如何克服以下问题感到困惑:
以前有没有人遇到过这样的问题,并且对如何概述这种解决方案的代码有任何想法(如果正在使用Python,如果它有助于引导我学习可以帮助我的特定功能,那么我正在使用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)
答案 0 :(得分:1)
如果我理解正确,这就是我要解决的问题。
X = 45
largest_jug = measured = 100
jug_sizes = [50, 6, 1]
steps = []
jug_to_use = 0
while measured != X:
if jug_to_use < len(jug_sizes) - 1: # we have smaller jugs in reserve
error_with_large_jug = min([abs(measured - jug_sizes[jug_to_use] - X), abs(measured + jug_sizes[jug_to_use] - X)])
error_with_small_jug = min([abs(measured - jug_sizes[jug_to_use + 1] - X), abs(measured + jug_sizes[jug_to_use + 1] - X)])
if error_with_small_jug < error_with_large_jug:
jug_to_use += 1
if measured > X:
measured -= jug_sizes[jug_to_use]
steps.append(('-', jug_sizes[jug_to_use]))
else:
measured += jug_sizes[jug_to_use]
steps.append(('+', jug_sizes[jug_to_use]))
print(steps)
屈服
[('-', 50), ('-', 6), ('+', 1)]
基本上是从使用最大的水罐开始,直到它处于下一个尺寸范围之内,依此类推。我们可以使用[30, 7, 1]
大小随机的水罐对其进行测试,然后再次看到它可以得出[('-', 30), ('-', 30), ('+', 7), ('-', 1), ('-', 1)]
的准确答案。
jug_sizes
应该按最大到最小的顺序订购X
中提供的数字来访问jug_sizes
(否则它将无限循环)[50, 12, 5]
,应跳过12个大小,否则解决方案将无法达到我确信您可以根据自己的具体情况为所有这些问题找到解决方案