V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2014-08-25 14:56:22 +08:00 · 3297 次点击
    这是一个创建于 3533 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2014-08-25 21:39:10 +08:00
    hahastudio
        1
    hahastudio  
       2014-08-25 15:17:55 +08:00   ❤️ 1
    vexfisher
        2
    vexfisher  
    OP
       2014-08-25 21:19:12 +08:00
    "If the random number generator can return a random integer p ≤ j < q for specified parameters p, q"


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

    https://gist.github.com/GTxx/2796868275375f6bd877
    eriale
        4
    eriale  
       2014-08-25 21:39:10 +08:00
    @eriale 具体没研究过。。。。少打一个字
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2899 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 07:46 · PVG 15:46 · LAX 00:46 · JFK 03:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.