代码之家  ›  专栏  ›  技术社区  ›  muwonge nicholus

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

  •  0
  • muwonge nicholus  · 技术社区  · 6 年前

    我想问的问题

    功能描述

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

    bonetrousle具有以下参数:

    n:要买的棍子的整数 k:商店里盒子大小的整数

    • n 从纸莎草纸所买的所有盒子中,可以总结出斯帕盖蒂的数量。
    • b 纸莎草纸将要购买的盒子的数量,然后将其中所有的sphagetti相加形成
    • k 将是商店中每个包含和增加sphagetti数量的总盒数例如8盒将按1盒==1 sphagetti,2盒==sphagetti的顺序排列。。。第八个盒子。

    如果号码 n

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

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

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

    样本输入

    • 4
    • 12 8 3
    • 10 3 3
    • 9 10 2

    样本输出

    • -1
    • 5 4
    • 1 8

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

    它应该在第一个测试用例上工作,但是我知道我没有很好地使用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循环占用了大量的空间和时间。

    0 回复  |  直到 6 年前