![](/img/trans.png)
[英]Trying to create a list of random variables without repetition in Python 3, can't get it to work
[英]Generating list of 2 variables in random repetition interval in range 1 to 3 in Python
我需要在電子表格中為我的實驗生成一個隨機的“X”和“O”符號列表。 總和應該是 200(100 個 X 和 100 個 O)。 連續不應該超過三個相同的符號 - 我是蟒蛇的新手,所以我很掙扎。 它可以在 Python 或 R 中。我很感激任何幫助。
a <- sample(rep(c("X","O"), each = 100), 200, replace = F)
table(a)
X O
100 100
import random
def random_ints_with_sum(n):
while n > 0:
r = random.randint(1, 3)
n -= r
if (n < 0):
n += r
else:
yield r
def print_chars(num, char):
for i in range(0,num):
print(char, end="")
num_o = 100
num_x = 100
list_of_o = list(random_ints_with_sum(num_o))
while True:
list_of_x = list(random_ints_with_sum(num_x))
if (len(list_of_o) == len(list_of_x)):
break
for i in range(0,len(list_of_o)):
print_chars(list_of_o[i],"O")
print_chars(list_of_x[i],"X")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.