Fisher–Yates shuffle

作为编程新手,又非本专业所学,在github上写博客似乎不自量力。然而记录本身也是学习的一部分,而这记录非此处不能写,那就开始吧。

w3cplus 看到洗牌算法似乎十分有趣,试着用python练习一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def shuffle(s):
import random
'''
From last item to first item, change position with a random item before it.
s: list of items
'''
i = len(s) - 1
while i > 0:
ran = random.sample(range(i),1)[0]
(s[ran],s[i]) = (s[i],s[ran])
i -= 1
return s

>>>shuffle("['1', '2', '3', '4', '5', '6', '7', '8', '9']")
['4', '7', '8', '6', '1', '2', '3', '9', '5']
>>>shuffle("['1', '2', '3', '4', '5', '6', '7', '8', '9']")
['8', '3', '1', '2', '9', '7', '4', '5', '6']
>>>shuffle("['1', '2', '3', '4', '5', '6', '7', '8', '9']")
['9', '7', '1', '3', '2', '8', '4', '5', '6']

还是挺好玩的嘛!

 上一篇

python alphabet