簡體   English   中英

如何在python中連續找到三個相同的值

[英]how to find three identical values in a row in python

假設從集合0、1、2,...,8、9中一次選擇一個隨機數,然后進行替換。使用10,000個模擬來估計連續選擇三個相同值所需的平均數。

這是我嘗試的代碼:

import numpy as np

newlist = 0*[0]
ct = 0
set = [0,1,2,3,4,5,6,7,8,9]
random = np.random.choice(set, size=1)
for i in range(10000):
    if random == random:
        ct +=1
        while ct == 3:
            newlist.append()
print(random)

我認為這就是您想要做的。 該代碼運行測試10000次,並且當最后三個值相等時,我們將迭代次數附加到結果上,並繼續進行下一個循環:

import numpy as np
from collections import deque

results = []
number_selection = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for _ in range(10000):
    _iterations = 1
    d = deque(maxlen=3)

    while True:
        random_value = np.random.choice(number_selection, size=1)
        if len(d) == 3 and len(set(d)) == 1:  # if last three items added to deque were equal we add the number of iterations to results and break to next loop
            results.append(_iterations)
            break  # break the while loop

        _iterations += 1
        d.append(random_value.item())

print('Average is: {0}'.format(float(sum(results)) / max(len(results), 1)))

希望這可以幫助!

算法

  1. 從您的集合中生成3個隨機選擇的項目的窗口
  2. 初始化一個計數器,該計數器將保存發現3個項目相等的次數
  3. 每次迭代時,將窗口向左移動並添加一個新的隨機選擇的項目
  4. 如果窗口中的所有項目都相等,則增加計數器
  5. 重復3和4,直到完成10000個模擬

import random

# [1, 2, 3] + 4 => [2, 3, 4]
def shift_left(arr, new_value):
    arr[0:len(arr) - 1] = arr[1:len(arr)]
    arr[len(arr) - 1] = new_value
    return arr

# [1, 1, 1] => True | [1, 2, 3] => False
def all_equal(window):
    for j in range(len(window) - 1):
        if window[j] != window[j+1]:
            return False
    return True

# Where real work happens
def avg(number_of_simulations, row_size, possible):
    number_of_equals = 0
    window = [random.choice(possible) for _ in range(row_size)] # window generation
    if all_equal(window):
        number_of_equals += 1

    for i in range(number_of_simulations - row_size):
        # Add new random number AND remove number from 3 iterations before
        window = shift_left(window, random.choice(possible))
        if all_equal(window):
            number_of_equals += 1 # Increment if all items are equal

    return number_of_equals

if __name__ == '__main__':
    possible_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    number_of_simulations = 10000
    row_size = 3
    answer = avg(number_of_simulations, row_size, possible_values)
    print(f'Found {answer} among {number_of_simulations}')

怎么樣:

opts = list(range(9))

# simulate once
def get_three(): 
    c = 1
    x = np.random.choice(opts, 1)
    i = 1
    while c < 3:
        x1 = np.random.choice(opts, 1)
        if x == x1:
            c += 1
        else:
            x = x1
            c = 1
        i += 1
    return i

# simulate n times
n = 10000 
result = sum([get_three() for i in range(n)]) / n
result # 90.5146

從理論上講,假設您的初始列表中有n數字,則期望值應為n * 1/n^3 ,即1/n^2 為了模擬它,我將進行以下操作:

import numpy as np

count = 0
num_iterations = 1000
numbers = [0,1,2,3,4,5,6,7,8,9]
for _ in range(num_iterations):
    if len(set(np.random.choice(numbers, 3, replace=True))) == 1:
        count += 1

print("Avg is {}".format(count/num_iterations))

說明:

由於具有替換的numpy.choice會從numbers均勻選擇三個成員,因此三個連續選擇相同數字的情況等同於基數為1的集合。如果將num_iterations增加到10000附近,您會看到它模擬了預期的精度(可接受的平均值約為0.01)的情況下。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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