如何创建暴力程序,生成所有可能的组合列表上限?

2024-05-13 21:13:09 发布

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

我必须创建一个函数,它接受一个上界列表,并返回一个包含所有可能组合的上界列表。例如,输入列表[1,1,2]将产生:

[ [ 0 , 0 , 0 ] , 
[ 0 , 0 , 1 ] , 
[ 0 , 0 , 2 ] , 
[ 0 , 1 , 0 ] , 
[ 0 , 1 , 1 ] ,
[ 0 , 1 , 2 ] , 
[ 1 , 0 , 0 ] , 
[ 1 , 0 , 1 ] , 
[ 1 , 0 , 2 ] , 
[ 1 , 1 , 0 ] , 
[ 1 , 1 , 1 ] , 
[ 1 , 1 , 2 ] , ]

到目前为止,我有:

def bounded_lists(upper_bound):
    start = [0] * len(upper_bound)
    print(start)
    while start != upper_bound:
        for i in range(1, len(upper_bound)+ 1):
            while start[-i] < upper_bound[-i]:
                start[-i] = start[-i] + 1
                print(start)
            start[-i] = 0
        break

但是,它只返回:

[0, 0, 0]
[0, 0, 1]
[0, 0, 2]
[0, 1, 0]
[1, 0, 0]

Tags: 函数in列表forlendefrangeupper
1条回答
网友
1楼 · 发布于 2024-05-13 21:13:09

您可以使用标准库itertools

from itertools import product

def bounded_lists(upper_bound):
    return list(product(*[range(ub + 1) for ub in upper_bound]))

工作原理如下:

>>> bounded_lists([1, 1, 2])
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 1, 0), (0, 1, 1), (0, 1, 2), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 1, 0), (1, 1, 1), (1, 1, 2)]

更新: 如果您对使用其他库感到不舒服,可以尝试递归地进行。你知道吗

def bounded_lists(upper_bound):
    result = []

    if len(upper_bound)== 0:
        result = []
    elif len(upper_bound)==1:
        result = [[i] for i in range(upper_bound[0] + 1)]
    else:
        first_bound = upper_bound[0]
        other_bound = upper_bound[1:]
        for i in range(first_bound + 1):
            for lst in bounded_lists(other_bound):
                result.append([i] + lst)
    return result

相关问题 更多 >