创建一个包含所有上限子集的列表(但lst [i]≤上限[i]) [英] Create a list that contains all subsets from an upperbound (but where lst[i] ≤ upper bound[i])
本文介绍了创建一个包含所有上限子集的列表(但lst [i]≤上限[i])的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试构建一个功能:
I'm trying to build a function that:
- 接受长度为n和的正整数列表作为参数.
- 返回长度为n的所有列表的列表,该列表由具有以下属性的非负整数组成:
- 对于列表
lst
,它适用于所有索引i,lst[i] ≤ upper bound[i]
- accepts as an argument a list of positive integers of length n and
- returns a list of all lists of length n consisting of non-negative integers with the following property:
- for a list
lst
it holds that for all indices i,lst[i] ≤ upper bound[i]
例如,如果输入列表为
[1, 1, 2]
,则输出为For example, if the input list was
[1, 1, 2]
, then the output would be[ [ 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_list(ub): f = len(ub) * [0] l = ub res = [f] while res[-1] != l: res += [lex_suc1(res[-1], ub)] return res def lex_suc1(lst, ub): res = lst[:] i = len(res) - 1 while res[i] == ub[i]: res[i] = 0 i -= 1 res[i] = ub[i] return res
给出输出:
[[0, 0, 0], [0, 0, 2], [0, 1, 0], [0, 1, 2], [1, 0, 0], [1, 0, 2], [1, 1, 0], [1, 1, 2]]
我无法理解如何添加缺少的列表,任何帮助都会很棒.
I'm not able to understand how to include the missing lists, any help woul be great.
推荐答案
这是一个选择:
from itertools import product for lst in product(range(2), range(2), range(3)): print(lst)
请注意,您的列表
[1, 1, 2]
在此处翻译为range(2), range(2), range(3)
.note that your list
[1, 1, 2]
translates torange(2), range(2), range(3)
here.或更直接地:
res = list(product(range(2), range(2), range(3))) # [(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)]
甚至:
lst = [1, 1, 2] res = list(product(*(range(i+1) for i in lst)))
这篇关于创建一个包含所有上限子集的列表(但lst [i]≤上限[i])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- for a list
- 对于列表
查看全文