暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

python函数设计和递归函数

原创 梯阅线条 2023-09-17
230

python函数设计和递归函数

1 python函数设计

python函数可以通过输入、输出、调用其他函数的方式与外部进行通信。

python函数设计时,使用return和可变参数作为输出,更容易理解和维护。
01python函数设计和递归函数图片2.png

img

2 python递归函数

python函数内部直接或间接调用本身的函数,称为递归函数。通常用于遍历未知的结构。

python递归函数条件:

(1) 每一次调用自己时,更接近于函数结果;

(2) 有一个终止函数处理的条件;

2.1 python递归求和

描述

python可以通过内置函数sum()求和,也可以通过递归函数求和。

递归求和:如果对象为空则终止求和,否则每次取剩余项的第1项与前面项相加。

示例

>>> def dirt_recsum(L): if not L:return 0#终止条件 return L[0]+dirt_recsum(L[1:])#直接调用本身;每次调用接近函数结果 >>> def indirt_recsum(L): if not L:return 0 return nonempty(L)#间接调用本身 >>> def nonempty(L): return L[0]+indirt_recsum(L[1:]) >>> L=[6,7,8,9,10] >>> dirt_recsum(L) 40 >>> indirt_recsum(L) 40 #内置求和sum()函数 >>> sum(L) 40

2.2 python非递归求和

示例

>>> def nonrecsum1(L):#不支持字符串列表 return 0 if not L else L[0]+nonrecsum1(L[1:]) >>> def nonrecsum2(L):#不支持空序列 return L[0] if len(L)==1 else L[0]+nonrecsum2(L[1:]) >>> def nonrecsum3(L):#不支持空序列 first,*rest=L return first if not rest else first+nonrecsum3(rest) >>> L=[6,7,8,9,10] >>> nonrecsum1(L) 40 >>> nonrecsum2(L) 40 >>> nonrecsum3(L) 40 >>> nonrecsum1([]) 0 #不支持空序列 >>> nonrecsum2([]) Traceback (most recent call last): File "<pyshell#51>", line 1, in <module> nonrecsum2([]) File "<pyshell#42>", line 2, in nonrecsum2 return L[0] if len(L)==1 else L[0]+nonrecsum2(L[1:]) IndexError: list index out of range #不支持空序列 >>> nonrecsum3([]) Traceback (most recent call last): File "<pyshell#52>", line 1, in <module> nonrecsum3([]) File "<pyshell#44>", line 2, in nonrecsum3 first,*rest=L ValueError: not enough values to unpack (expected at least 1, got 0) >>> SL=list('梯阅线条') >>> SL ['梯', '阅', '线', '条'] #不支持字符串列表 >>> nonrecsum1(SL) Traceback (most recent call last): File "<pyshell#57>", line 1, in <module> nonrecsum1(SL) File "<pyshell#40>", line 2, in nonrecsum1 return 0 if not L else L[0]+nonrecsum1(L[1:]) File "<pyshell#40>", line 2, in nonrecsum1 return 0 if not L else L[0]+nonrecsum1(L[1:]) File "<pyshell#40>", line 2, in nonrecsum1 return 0 if not L else L[0]+nonrecsum1(L[1:]) [Previous line repeated 1 more time] TypeError: can only concatenate str (not "int") to str >>> nonrecsum2(SL) '梯阅线条' >>> nonrecsum3(SL) '梯阅线条'

2.3 python递归任意嵌套

python递归函数可以遍历任意结构的嵌套。

示例

>>> def recsumtree(L): total=0 for x in L: if not isinstance(x,list): total+=x else: total+=recsumtree(x) return total >>> L=[1 , [2, [ 3, 4] , 5] , 6, [7 , 8]] >>> recsumtree(L) 36

3 END

本文首发微信公众号:梯阅线条

更多内容参考python知识分享或软件测试开发目录。

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

文章被以下合辑收录

评论