推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
vexfisher
V2EX  ›  Python

关于 Shuffle 实现代码的三点疑惑

  •  
  •   vexfisher · Aug 25, 2014 · 4146 views
    This topic created in 4301 days ago, the information mentioned may be changed or developed.
    python的shuffle代码是通过随机交换两个下标的值来达到洗牌的目的。
    疑惑1:为什么要用倒序循环?
    疑惑2:xrange中为什么不是从0开始?
    疑惑3:在语句`j= _int(random() * (i+1))`中,j可以取到的最大值是i,这样岂不是达不到交换值的目的了?我的理解是`j= _int(random() * i)` ,这样保证 0<j<i 。


    def shuffle(self, x, random=None):

    if random is None:
    random = self.random
    _int = int
    for i in reversed(xrange(1, len(x))):
    # pick an element in x[:i+1] with which to exchange x[i]
    j = _int(random() * (i+1))
    x[i], x[j] = x[j], x[i]

    python新手先谢过大家了。
    4 replies    2014-08-25 21:39:10 +08:00
    vexfisher
        2
    vexfisher  
    OP
       Aug 25, 2014
    "If the random number generator can return a random integer p ≤ j < q for specified parameters p, q"


    @hahastudio 谢过haha君
    eriale
        3
    eriale  
       Aug 25, 2014   ❤️ 1
    具体研究过,不过洗牌程序的随机性你可以通过代码来测试,就是对一个队列反复洗牌,并统计出现的位置。
    已经有人讨论过怎么测试洗牌程序了:
    http://coolshell.cn/articles/8593.html

    https://gist.github.com/GTxx/2796868275375f6bd877
    eriale
        4
    eriale  
       Aug 25, 2014
    @eriale 具体没研究过。。。。少打一个字
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5347 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 07:31 · PVG 15:31 · LAX 00:31 · JFK 03:31
    ♥ Do have faith in what you're doing.