我的Fisher-Yates shuffle实现的随机分布问题?

时间:2017-10-01 03:46:00

标签: python

本周我试图学习Fisher-Yates shuffle,我想知道是否有一种很好的方法来实现均匀随机分布而不在shuffle函数中使用python build。

https://bost.ocks.org/mike/shuffle/

我试图以天真的洗牌方式解决它,但是当你必须实现统一的随机分布时它会变得棘手。

这是我构建的一些示例代码。

# I'll implement the shuffle in place algorithm then test it # to make sure it fits the statistical definition of a uniform random
# shuffle

import random


def get_random(floor, ceiling):
    """return a random number in the closed interval (floor, ceiling)"""
    return random.randint(floor, ceiling)  # randint does this already


# this is non-uniform naive shuffle
# stripped of comments, it differs from the in_place_uniform_shuffle
# by 1 character. (A critical 1 character difference!)

# using statistics in the unit tests, it can be seen that the naive
# shuffle never converges on a uniform shuffling, empirically, the
# variance can at times be seen to increase even with increasing
# repetitions.


def naive_shuffle(the_list):

    # for each index in the list
    for first_index in xrange(0, len(the_list) - 1):

        # grab a random other index
        second_index = get_random(first_index, len(the_list) - 1)

        # and swap the values
        if second_index != first_index:
            the_list[first_index], the_list[second_index] = \
                the_list[second_index], the_list[first_index]

https://repl.it/LrSA/3

我感谢任何反馈

0 个答案:

没有答案