【问题标题】:How to determine all the possible combinations given a list of binary numbers (0s or 1s or None) of length n?给定长度为 n 的二进制数(0 或 1 或无)列表,如何确定所有可能的组合?
【发布时间】:2023-04-03 17:53:01
【问题描述】:

我想编写一个函数来确定给定二进制数(0 或 1 或无)长度为 n 的列表的所有可能组合。

假设我的列表的长度应该是 3。比期望的输出应该是:

arrangement_1 = [0,0,0]
arrangement_2 = [1,0,0]
arrangement_3 = [0,1,0]
arrangement_4 = [0,0,1]
arrangement_5 = [1,1,0]
arrangement_6 = [1,0,1]
arrangement_7 = [0,1,1]
arrangement_8 = [1,1,1]
arrangement_9 = [0,0,None]
arrangement_10 = [None,0,0]
arrangement_11 = [0,None,0]
arrangement_12 = [0,None,None]
arrangement_13 = [None,0,None]
arrangement_14 = [None,None,0]
arrangement_15 = [1,1,None]
arrangement_16 = [None,1,1]
arrangement_17 = [1,None,1]
arrangement_18 = [1,None,None]
arrangement_19 = [None,1,None]
arrangement_20 = [None,None,1]
arrangement_21 = [None,1,0]
arrangement_N  = [...]

我通过给它一个 1s/0s 和 None 元素的随机初始状态来尝试以下函数,但它没有给我想要的输出(我也尝试了其他函数,比如组合 - 也没有想要的输出):

def calc_permutations(list = []): # Takes list with n elements and calculates no of permutations and return dictionary of number of permutations and states

    possible_states = [] 

    for i in permutations(list,len(list)):
        possible_states.append(i)

    possible_states = {"noOfstates": len(possible_states), "states": possible_states} 
    return possible_states 

【问题讨论】:

  • 你可能会喜欢itertools.combinations
  • 我已经尝试过使用组合,但是使用它时我没有得到我想要的输出。假设我给它一个 [1,1,0,0,0,0,0,0,0] 的列表,并根据列表 (9) 的长度设置 r。它只是返回 [1,1,0,0,0,0,0,0,0]。

标签: python combinations permutation


【解决方案1】:

你可以使用itertools.product:

from itertools import product
alphabet = [0, 1, None]
for x in product(alphabet, repeat=3):
  print(x)

输出:

(0, 0, 0)
(0, 0, 1)
(0, 0, None)
(0, 1, 0)
(0, 1, 1)
(0, 1, None)
(0, None, 0)
(0, None, 1)
(0, None, None)
(1, 0, 0)
(1, 0, 1)
(1, 0, None)
(1, 1, 0)
(1, 1, 1)
(1, 1, None)
(1, None, 0)
(1, None, 1)
(1, None, None)
(None, 0, 0)
(None, 0, 1)
(None, 0, None)
(None, 1, 0)
(None, 1, 1)
(None, 1, None)
(None, None, 0)
(None, None, 1)
(None, None, None)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 2021-10-20
    • 1970-01-01
    • 2020-11-19
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多