如何在python列表中找到以n个组合求和到给定数字的数字组合?

2024-06-28 15:34:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试的问题

功能描述

在下面的编辑器中完成bonetrousle函数。它应该返回一个整数数组

bonetrousle具有以下参数:

n:要买的棍子的整数 k:商店携带的盒子大小的整数 b:要买的箱子的整数

编辑:

  • 该函数将n作为从Papyrus购买的所有盒子中汇总的sphagetti棒数
  • b是Papyrus将购买的盒子数量,然后将其中的所有sphagetti相加形成n
  • k将是商店中每个包含和增加sphagetti数量的盒子总数。例如,8个盒子的顺序为1个盒子==1个sphagetti,2个盒子==sphagetti。。。第八个盒子

如果纸莎草纸所需的盒子数量比库存中的盒子数量多,则返回-1

我希望这能进一步澄清这个问题

通过HackerRack也可以更好地理解这个问题 https://www.hackerrank.com/challenges/bonetrousle/problem

如果有解决方案,打印一行不同的空格分隔整数,其中每个整数表示纸草必须购买的每个盒子中面条的数量。 如果有多个可能的解决方案,则可以打印其中任何一个。不要打印任何前导或尾随空格或额外的换行符

样本输入

  • 四,
  • 12 8 3
  • 103
  • 9102
  • 9102

样本输出

  • 2 3 7
  • -一,
  • 5.4
  • 18

**这是我的解决方案**

它应该在第一个测试用例上工作,但我知道我没有很好地使用b(skeleton想要购买的盒子数量),因为我对如何进行感到困惑

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())
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


所以,我真的需要你的帮助来自动化for循环或任何替代解决方案,因为我知道许多for循环占用了大量的空间和时间


Tags: oftheinfor数量if整数解决方案