2016-10-03 56 views
0

我想列出出現概率原因的所有可能的0和1排列六次。0和1的所有可能性排列

我是這樣開始的,以爲這是一塊蛋糕;直到列出所有組合,代碼應該使值隨機化。 然而,一旦0和1是在它停止列表,我想「爲範圍在6」將給出這樣的事情:

"0,0,0,0,0,0"(其爲0的可能性和1)

"1,1,1,1,1,1"(其也爲0的可能性和1)

我的電流輸出爲「0,1」

我怎麼能組項目的6塊放在一起,讓程序繼續填充值了,除非組合已經在我的列表?
我知道共有64個組合,因爲2^6。

import math 
import random 

    a = 63; 
    b = 1; 
    sequences = []; 
    while (b < a): 
     for i in range(6): 
      num = random.randint(0 , 1) 
      if(num not in sequences): 
       sequences.append(num) 
       b += 1; 
      else: 
       b += 1; 

    print(sorted(sequences)); 

回答

1

我不明白如果您正在尋找解決方案或修復您的代碼。如果你只是尋找一個解決方案,您可以使用itertools像這樣做更容易,更有效:

>>> from itertools import * 
>>> a = list(product([0,1],repeat=6)) #the list with all the 64 combinations 
0

我明白你要檢查你多少次迭代達到64種可能的組合。在這種情況下,這個代碼是:

import math 
import random 

combs = set() 
nb_iterations = 0 
while len(combs)<64: 
    nb_iterations+=1 
    a = (tuple(random.randint(0,1) for _ in range(6))) 
    if a in combs: 
     pass 
    else: 
     combs.add(a) 

print("Done in {} iterations".format(nb_iterations)) 

我跑了幾次,它花了大約300/400迭代,以獲得完整列表。的輸出

實施例:

Done in 313 iterations 
Done in 444 iterations 
Done in 393 iterations 
相關問題