python中如何实现简单的洗牌算法
python中如何实现简单的洗牌算法
在我们玩的牌类游戏中,通过洗牌算法的设计,落在数组某个位置上的概率是相等的,那你知道如何使用python设计一个简单的洗牌算法吗?其实实现很简单,使用random模块shuffle方法即可实现洗牌算法,本文小编带领大家设计一个简单的洗牌算法。
1、洗牌算法
算法思想就是从原始数组中随机抽取一个新的数字到新数组中,其本质是对数组元素进行随机重排。
数组中每个元素经过洗牌算法后落在数组某个位置上的概率是相等的,洗牌算法在牌类游戏中非常有用。
2、洗牌算法的简单实现
random模块shuffle方法实现洗牌算法
shuffle()方法:将列表的所有元素随机排列
importrandom
defshuffel(lst):
l=len(lst)
ifl<=1:
returnlst
i=0
whilel>1:
p=int(random.random()*l)
lst[i],lst[i+p]=lst[i+p],lst[i]
i+=1
l-=1
returnlst
print(shuffel([1,2,2,3,3,4,5,10]))
以上就是python中使用random模块shuffle方法实现洗牌算法的代码操作,需要注意的是习方法返回空值,会影响原数组哦~更多Python学习教程请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python中wordcloud库如何生成词云?
python中wordcloud库如何生成词云?可能有些小伙伴不了解词云是什么,其实主要作用是为了快速解决类问题的方法,它能够实现凸显关键词,快速帮助...详情>>
2023-11-11 02:14:00
python的概率分布有哪些类型?
python的概率分布有哪些类型?python数据可视化。无非是把各种各样的数据以视图的形式展现出来,可以更直观的分析数据。python的数据可视化离不...详情>>
2023-11-11 00:43:24
python中socket如何测试程序?
python中socket如何测试程序?1、编写server的步骤(1)是创建socket对象。调用socket构造函数。如:socket=socket.socket(family,type)(2)是详情>>
2023-11-11 00:19:01
python函数装饰器的应用过程
python函数装饰器的应用过程1、应用过程一般是定义在一个独立模块中,使用时会被导入到其它模块;函数装饰器会在内部定义一个新函数,然后返回。...详情>>
2023-11-10 22:33:56热门推荐
python汉诺塔递归函数是什么?
沸Python3中的tuple函数是什么?
热python关键字有哪些?
热python中doctest模块如何使用?
新python中定时器的实现方式
python中写入文件的出错解决
python中wordcloud库如何生成词云?
python中pandas_datareader库怎么用?
python中SQLAlchemy是什么?
python中如何实现简单的洗牌算法
python的概率分布有哪些类型?
python中socket如何测试程序?
pythonLogging是什么?
python如何应用于数据的基础统计分析
技术干货






