一、Fisher-Yates算法
1.算法定义
Fisher-Yates算法是一种获取随机序列的算法
2.代码示例
旧方法
import random
n = int(input())
list = []
# 自定义初始序列
for i in range(0, n):
list.insert(i, int(input()))
print("原始序列:" + str(list))
# 旧版本
final_list = []
for i in range(0, n):
# 随机抽取元素位置
pos = random.randint(0, n -1 - i)
# 将该位置的元素放入新序列中
final_list.insert(i, list[pos])
j = pos
# 将该元素后面的元素向前移动,确保不重复
list.pop(pos)
print("新序列:" + str(final_list))
新方法
# 改进版本 将选中的元素和第i位上的元素交换
for i in range(0, n):
# 随机抽取元素位置
pos = random.randint(i, n - 1)
# 将该位置的元素放入新序列中
old = list[i]
list[i] = list[pos]
list[pos] = old
print("新序列:" + str(list))