簡體   English   中英

使用python生成具有限制和一定長度的給定數字的隨機列表

[英]generating random list of given numbers with limitations and certain length with python

我想在以下條件下生成隨機 1 和 0 的二進制矩陣 (16*15):

  • 每行不超過 2 個連續相等的數字。
  • 如果每行有連續相等的數字,則不允許超過 3 對。
  • 每行1和0的數量必須分別為8和7或7和8。

我有這個用於生成隨機列表的代碼,但我不知道如何在隨機部分添加條件。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM