Python:查找与给定和匹配的元素组合

2024-10-04 03:27:50 发布

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

假设给了我一个和S,也给了我一些固定值的元素a,b,c和d。我正在尝试编写一个算法,试图找到给定和S的固定值的任意长度的组合(这意味着它可以是a+b,或a+a+a…+a)

总和和固定值是二进制的,它们包含6位。这意味着在溢出发生之前,可能的最大和实际上是63,我们返回到0,这也意味着固定值实际上可以大于所讨论的和。

def foo(array, c):
    v0 = int(convert(Ch[0]), 2) #These four lines here are simply converting my fixed values which are in an array into binary integers with a function, it is not important to the essence of the question.
    v1 = int(convert(Ch[1]), 2)
    v2 = int(convert(Ch[2]), 2)
    v3 = int(convert(Ch[3]), 2)
    rowlist = [v0, v1, v2, v3] #Create a list of the fixed values to iterate with a loop
    responsesum = 0
    challenger = int(convert(c), 2) #This is the Sum that we will match our combinations against, it is also a binary number
    print(f'The challenger is {challenger}')
    for i in range(4):
        if (rowlist[i] == challenger):
            return True
        for j in range(4):
            responsesum = rowlist[i] + rowlist[j]
            while responsesum >= 64: #This while loop attempts to get the 6bit value when overflow occurs (the combination has a value of more than 64, aka more than 7 bits)
                print(f'Overflow response is {responserow}')
                responsesum = responsesum - int(str(111111), 2) - int(str(1), 2)
            print(f'The sum is {responsesum}')

            if (responsesum == challenger):
                return True
            for k in range(4):
                responsesum = rowlist[i] + rowlist[j] + rowlist[k]
                while responsesum >= 64:
                    responsesum = responsesum - int(str(111111), 2) - int(str(1), 2)
                print(f'The sum is {responsesum}')
                if (responsesum == challenger):
                    return True

如您所见,这是一段非常不雅观的代码,事实上,当我无法找到给定总和的组合时,我必须通过继续添加for循环来手动决定组合的长度。

是否有一种方法可以优雅地实现这一点(例如,如果没有解决方案,算法可能会决定添加一个新的for循环,并将组合长度增加1?


Tags: ofthetoinconvertforisch