python语言的全排列怎么提速?
python从n个不同元素中任取m(m≤n)个元素,按照一定的顺序排列起来,叫做从n个不同元素中取出m个元素的一个排列。当m=n时所有的排列情况叫全排列。显然全排列很费时,这里用到了yield方法,全排列速度加倍
什么是yield()方法?
首先,如果你还没有对yield有个初步分认识,那么你先把yield看做“return”,这个是直观的,它首先是个return,普通的return是什么意思,就是在程序中返回某个值,返回之后程序就不再往下运行了。看做return之后再把它看做一个是生成器(generator)的一部分(带yield的函数才是真正的迭代器),好了,如果你对这些不明白的话,那先把yield看做return,然后直接看下面的程序,你就会明白yield的全部意思了:
deffoo():
print("starting...")
whileTrue:
res=yield4
print("res:",res)
g=foo()
print(next(g))
print("*"*20)
print(next(g))
代码的输出:
starting...
4
********************
res:None
使用yield()方法的全排列:
defperm(arr,pos=0):
ifpos==len(arr):
yieldarr
foriinrange(pos,len(arr)):
arr[pos],arr[i]=arr[i],arr[pos]
for_inperm(arr,pos+1):yield_
arr[pos],arr[i]=arr[i],arr[pos]
foriinperm([1,2,3,4]):
printi
以上内容为大家介绍了Python培训之语言的全排列怎么提速?,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python装饰器管理函数和类的注意点
python装饰器管理函数和类的注意点本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、注意点(1)用装饰器修饰的函数或类主要应用场...详情>>
2023-11-07 21:15:48
python输入数字变成月份
python输入数字变成月份1、思路说明可计算给定区间的时间差,即两者之间共包含几个月。然后由第一个月(开始时间)逐渐累积,最后得到给定时间区...详情>>
2023-11-07 18:13:40
pythonGevent的使用
1、可以通过gevent轻松实现并发同步或异步编程。gevent中使用的主要模式是Greenlet,它是以C扩展模块的形式访问Python的轻量级协程。2、Greenle...详情>>
2023-11-07 17:51:06
python怎么生成xml文件
用python内置的xml.dom可以对xml文件进行解析处理。什么是xml?XML指可扩展标记语言(EXtensibleMarkupLanguage)XML是一种标记语言,很类似HTMLXM...详情>>
2023-11-07 16:53:54热门推荐
技术干货






