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)
定义:
        如果一个函数使用了yield语句,那么他就死一个生成器函数。如enumerate()就是用生成器实现的。
enumerate函数原型:
def enumerate(sequence,start=0):
    n = start
    for elem in sequence:
        yield n,elem
        n += 1

enumerate应用:

生成器的函数内部调用:
首先需要理解,生成器实现了迭代器的协议,内部有__iter__和__next__方法。
其次,第一次调用next(generator_obj),函数执行到yield value表达式,没有执行赋值的操作,value的值为1;第二次next(generator_obj),函数会从赋值开始执行,执行到yield value表达式,yield表达式默认值为None。
最后,执行generator_obj.close()会关闭生成器。

注意:上面提到了yield表达式有一个默认值,如何控制yield表达式的值呢?
生成器有一个send方法,next(generator_obj)相当于generator_obj.send(None)。send方法的实参就是yield表达式的值。
        

0 0
原创粉丝点击