繁体   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