【发布时间】:2020-06-25 23:29:27
【问题描述】:
我正在尝试创建一个函数,其中:
- 输出列表由输入列表中的随机数生成
- 输出列表是指定长度并添加到指定总和
例如。我指定我想要一个长度为 4 且加起来为 10 的列表。从输入列表中提取随机数,直到满足条件。
我觉得我试图使用递归来解决这个问题都是错误的。任何帮助将不胜感激!!!
编辑:有关此问题的更多上下文....它将是一个随机敌人生成器。
最终目标输入列表将来自 CSV 中名为 XP 的列。 (我打算使用熊猫模块)。但是这个 CSV 将在一个列中列出敌人名称,在另一列中有 XP,在另一列中有 Health,等等。所以最终目标是能够指定敌人的总数以及这些敌人之间的 XP 总和应该是多少并使用适当的信息生成列表。例如。 5 个敌人,他们之间总共有 200 XP。结果可能是 -> Apprentice Wizard(50 xp)、Apprentice Wizard(50 xp)、Grung(50)、Xvart(25 xp)、Xvart(25 xp)。输出列表实际上需要包含所选项目的所有行信息。如本例所示,在输出中复制完全没问题。这实际上在游戏的叙述中更有意义。
csv --> https://docs.google.com/spreadsheets/d/1PjnN00bikJfY7mO3xt4nV5Ua1yOIsh8DycGqed6hWD8/edit?usp=sharing
import random
from random import *
lis = [1,2,3,4,5,6,7,8,9,10]
output = []
def query (total, numReturns, myList, counter):
random_index = randrange(len(myList)-1)
i = myList[random_index]
h = myList[i]
# if the problem hasn't been solved yet...
if len(output) != numReturns and sum(output) != total:
print(output)
# if the length of the list is 0 (if we just started), then go ahead and add h to the output
if len(output) == 0 and sum(output) + h != total:
output.append(h)
query (total, numReturns, myList, counter)
#if the length of the output is greater than 0
if len(output) > 0:
# if the length plus 1 is less than or equal to the number numReturns
if len(output) +1 <= numReturns:
print(output)
#if the sum of list plus h is greater than the total..then h is too big. We need to try another number
if sum(output) + h > total:
# start counter
for i in myList:# try all numbers in myList...
print(output)
print ("counter is ", counter, " and i is", i)
counter += 1
print(counter)
if sum(output) + i == total:
output.append(i)
counter = 0
break
if sum(output) + i != total:
pass
if counter == len(myList):
del(output[-1]) #delete last item in list
print(output)
counter = 0 # reset the counter
else:
pass
#if the sum of list plus h is less than the total
if sum(output) + h < total:
output.append(h) # add h to the list
print(output)
query (total, numReturns, myList, counter)
if len(output) == numReturns and sum(output) == total:
print(output, 'It worked')
else:
print ("it did not work")
query(10, 4, lis, 0)
【问题讨论】:
-
数字可以重复吗?例如
[2, 2, 3, 3]是query(10, 4, lis, 0)的有效解决方案吗? -
嗨尼克,是的,数字可以重复。 [2, 2, 3, 3] 是我正在寻找的完美解决方案。谢谢!
-
您接受的答案不会生成
[2, 2, 3, 3]作为解决方案。 -
感谢您发现尼克,我没有意识到。在这种情况下,实际上最好使用重复的数字。
-
这似乎是背包问题的化身
标签: python list recursion random sum