如何在python列表中找到以n个组合求和到给定数字的数字组合?
我正在尝试的问题 功能描述 在下面的编辑器中完成bonetrousle函数。它应该返回一个整数数组 bonetrousle具有以下参数: n:要买的棍子的整数 k:商店携带的盒子大小的整数 b:要买的箱子的整数 编辑:如何在python列表中找到以n个组合求和到给定数字的数字组合?,python,for-loop,idioms,Python,For Loop,Idioms,我正在尝试的问题 功能描述 在下面的编辑器中完成bonetrousle函数。它应该返回一个整数数组 bonetrousle具有以下参数: n:要买的棍子的整数 k:商店携带的盒子大小的整数 b:要买的箱子的整数 编辑: 该函数将n作为从Papyrus购买的所有盒子中求和的sphagetti棒数 b是Papyrus将购买的盒子数量,然后将其中的所有sphagetti相加形成n k是商店中每个包含和增加sphagetti数量的盒子总数,例如,8个盒子的顺序为1个盒子==1个sphagetti,2个
- 该函数将n作为从Papyrus购买的所有盒子中求和的sphagetti棒数
- b是Papyrus将购买的盒子数量,然后将其中的所有sphagetti相加形成n
- k是商店中每个包含和增加sphagetti数量的盒子总数,例如,8个盒子的顺序为1个盒子==1个sphagetti,2个盒子==sphagetti。。。第八个盒子
- 四,
- 12 8 3
- 103
- 9102
- 9102
- 2 3 7
- -一,
- 5.4
- 18
def bonetrousle(n, k, b):
# list the range for the store boxes {done}
# find if the number of boxes required by skeleton are accessible from the store
# find a combination that gives me the number of sphagetti required by skeleton
inventory=[item for item in range(1,k+1)]
list_of_outcome=[]
# if sum of the items in the store is greater than the number of
# individual sphagetti's wanted, this means,is possible to get
# what skeleton came looking for
if sum(inventory)>n:
if b==2:
for i in inventory:
for j in inventory:
if i+j==n:
list_of_outcome.append("{}{}".format(
i,j
))
else:
for i in inventory:
for j in inventory:
for k in inventory:
if i+j+k==n:
list_of_outcome.append("{}{}{}".format(
i,j,k
))
else:
return ("-1")
if list_of_outcome!=[]:
return ((random.choice(list_of_outcome)).strip())
所以,我真的需要你的帮助来自动化for循环或任何替代解决方案,因为我知道许多for循环占用了大量的空间和时间 就目前而言,这不是一个好问题。太长了,让人困惑。请重新编写,以便更清楚地说明a)该程序到底应该做什么;b) 你已经尝试过的。嗨@Erichkizmueller,我编辑了这个问题,我的解决方案也附在附件中。为了更好地理解这个问题,请通读编辑或者帮助我访问我试图解决的黑客排名问题
Compiler Message
Wrong Answer
Input (stdin)
Download
4
12 8 3
10 3 3
9 10 2
9 10 2
Your Output (stdout)
3 5 4
- 1
8 1
8 1
Expected Output
Download
2 3 7
-1
5 4
1 8