python递归、迭代器和生成器在算法中的运用
来源:互联网 发布:如何入门数据分析师 编辑:程序博客网 时间:2024/05/21 08:46
- 递归
程序调用自身的编程技巧称为递归。递归做为一种算法在程序设计语言中广泛应用。 一个过程或函数在其定义或说明中有直接或间接调用自身的一种方法,它通常把一个大型复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解,递归策略只需少量的程序就可描述出解题过程所需要的多次重复计算,大大地减少了程序的代码量。递归的能力在于用有限的语句来定义对象的无限集合。一般来说,递归需要有边界条件、递归前进段和递归返回段。当边界条件不满足时,递归前进;当边界条件满足时,递归返回。
应用一:文件的查找
- 1.使用os.walk()
# -*- coding:utf-8 -*-
import os,sys
def traversalfile(path):
#root:当前目录;dirs:当前目录包含的文件夹;files:当前路径包含的文件
for root,dirs,files in os.walk(path):
for file in files:
if file.endswith('.txt')
print('{}\n'.format(file))
if __name__ == '__main__':
filePath = "D:/python"
if os.path.isdir(filePath):
traversalfile(filePath)
else:
print('Info: {} not exist!'.format(filePath))
sys.exit(1)
- 2.使用递归
# -*- coding:utf-8 -*-
import os,sys
def getVector(path):
#当前目录的文件夹和文件
dir_lists = os.listdir(path)
for dir_list in dir_lists:
#如果是文件
if os.path.isfile(os.path.join(path,dir_list)):
print('%s\n' % (os.path.join(path,dir_list)))
#如果是文件夹,递归查询该文件夹
if os.path.isdir(os.path.join(path,dir_list)):
getVector(os.path.join(path,dir_list))
if __name__ == '__main__':
file_path = "D:/python"
if os.path.isdir(filePath):
getVector(file_path)
else:
print('Info: {} not exist!'.format(file_path))
sys.exit(0)
- 迭代器(Iterators)
python手册的定义:
Iterators are required to have an__iter__() method that returns the iterator object itself so every iterator is also iterable and may be used in most places where other iterables are accepted.
Repeated calls to the iterator’s__next__() method (or passing it to the built-in function next()) return successive items in the stream. When no more data are available aStopIteration exception is raised instead.
python语言的迭代器内建在语言中,带有__iter__()和__next__()方法。通过__iter__()方法,返回一个迭代器对象;再通过next()方法返回当前的元素,并指向下一个元素的位置,如果当前位置是最后一个元素,则抛出StopIteration异常。
iterable:
An object capable of returning its members one at a time. Examples of iterables include all sequence types (such as list, str, and tuple) and some non-sequence types like dict, file objects, and objects of any classes you define with an __iter__() or __getitem__() method.
一些变量类型不是迭代器,但是他们有__iter__()或者__getitem__方法,可以转化成迭代器,如list,str,tuple和dict,file objects。
例如list:
迭代器的应用:
- 生成器(generator)
def enumerate(sequence,start=0):
n = start
for elem in sequence:
yield n,elemn += 1
enumerate应用:
- python递归、迭代器和生成器在算法中的运用
- Python基础知识7:生成器和迭代器、递归
- python中的生成器和迭代器
- python中的迭代器和生成器
- Python中的迭代器和生成器
- python中的生成器和迭代器
- python中的生成器和迭代器
- python中的迭代器和生成器
- python中的迭代器和生成器
- python中的迭代器和生成器学习
- 深入讲解Python中的迭代器和生成器
- Python基础教程----迭代器和生成器,递归,八皇后(2)
- 循环和递归在算法中的应用
- 循环和递归在算法中的应用
- 循环和递归在算法中的应用
- python迭代器和生成器
- Python 迭代器和生成器
- Python 迭代器和生成器
- JavaScript_JavaScript 扩展函数
- iOS 添加ttf字体
- java集合18--Iterator和Enumeration比较
- Protocol Buffer编码方式
- poj 上的dp 留着慢慢写
- python递归、迭代器和生成器在算法中的运用
- 实例对比WPF中的Timer和DispatcherTimer
- 第11周项目5摩托车继承自行车和机动车
- CSS代码中-webkit,-moz,-o,-ms含义
- Ubuntu下载Android源码
- 网络(Java核心技术卷Ⅱ)
- python字符串处理
- 关于Div的宽度与高度的100%设定
- 67. Add Binary