How to generate all possible combinations of N slots with V possible values? [duplicate]

梦想的初衷 提交于 2019-12-08 03:22:21

问题


I have N ordered slots. Each slot has a value within V possible values

N = 4 # number of objects (e.g. slots)
possible_values = ['A','B']
V = len(possible_values )

How would it be possible to generate the list of all possible combinations in Python? For instance, when V=2 and N=4, I would like to get the following list of the 2**4 different combinations:

combinations = [
    [ 'A', 'A', 'A', 'A' ], # combination 0
    [ 'A', 'A', 'A', 'B' ], # combination 1
    [ 'A', 'A', 'B', 'A' ], # combination 2
    [ 'A', 'A', 'B', 'B' ], # combination 3
    [ 'A', 'B', 'A', 'A' ], # combination 4
    [ 'A', 'B', 'A', 'B' ], # combination 5
    [ 'A', 'B', 'B', 'A' ], # combination 6
    [ 'A', 'B', 'B', 'B' ], # combination 7
    [ 'B', 'A', 'A', 'A' ], # combination 8
    [ 'B', 'A', 'A', 'B' ], # combination 9
    [ 'B', 'A', 'B', 'A' ], # combination 10
    [ 'B', 'A', 'B', 'B' ], # combination 11
    [ 'B', 'B', 'A', 'A' ], # combination 12
    [ 'B', 'B', 'A', 'B' ], # combination 13
    [ 'B', 'B', 'B', 'A' ], # combination 14
    [ 'B', 'B', 'B', 'B' ], # combination 15
]

I would like the code to work when N and V vary. For example, when N=9 slots and V=4 possible values, I expect the list of the 4**9=262144 possible combinations.


回答1:


N = 4 # number of objects (e.g. slots)
possible_values = ['A','B']

result = itertools.product(possible_values, repeat=N)

print(list(result))


来源:https://stackoverflow.com/questions/51198109/how-to-generate-all-possible-combinations-of-n-slots-with-v-possible-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!