[英]How can Python keep generating a random list of numbers until it equals to a certain made-up list?
[英]generating random list of given numbers with limitations and certain length with python
我想在以下條件下生成隨機 1 和 0 的二進制矩陣 (16*15):
我有這個用於生成隨機列表的代碼,但我不知道如何在隨機部分添加條件。
import random
import numpy as np
arr_len = 15
num_ones = 8
pattern = np.zeros(arr_len, dtype=int)
idx = np.random.choice(range(arr_len), num_ones, replace=False)
pattern[idx] = 1
print (pattern)
在這種情況下,很容易創建所有可能的此類行的列表(只有 504 個),然后從隨機行創建矩陣。
下面的代碼通過查看每個可能的行來實現這一點,它通過以二進制格式迭代數字 0 到 2^15-1 來生成這些行。 然后它檢查三個條件,並存儲有效行。 為了生成矩陣,它會隨機繪制 16 行。
def BinaryString(n):
s = bin(n)[2:]
return '0'*(15-len(s)) + s
validRows = []
for binaryNum in range(2**15):
s = BinaryString(binaryNum)
#Check Condition 3
if np.sum([num == '0' for num in s]) not in [7,8]:
continue
#Check Condition 1
hasTriple = False
for i in range(13):
if s[i] == s[i+1] and s[i+1] == s[i+2]:
hasTriple = True
break
if hasTriple:
continue
#Check Condition 2
doubles = np.sum([s[i] == s[i+1] for i in range(14)])
if doubles > 3:
continue
#If it is good, append it to the list
validRows.append([int(i) for i in s])
validRows = np.vstack(validRows)
def CreateMatrix():
rows = np.random.randint(0,len(validRows),16)
return np.vstack([validRows[i] for i in rows])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.