Python中递归思想,打印斐波那契数列

阅读: 评论:0

Python中递归思想,打印斐波那契数列

Python中递归思想,打印斐波那契数列

目录

一.递归访问目录:目录中嵌套目录,有层次的列出所有的文件和文件夹

二.定义一个嵌套函数

三.定义一个递归函数:打印菲波那契数列F(n)=F(n-1)+F(n-2)(n>=2,F(0)=0,F(1)=1)

四.对列表进行排序

五.利用map函数:计算三个列表,相同位置元素之和.

六.利用filter函数过滤列表中所有带a的字符串.

七.利用reduce计算1+2+3+...+100之和


一.递归访问目录:目录中嵌套目录,有层次的列出所有的文件和文件夹

先在D盘新建一个目录test,test目录中包含一个test1文件夹和文件,test1文件夹中包含test2和test.xsl,test2文件夹中包含test3和test.doc,test2文件夹中包含

import osdef list_dir_content(dir_path, count=0):   for file_name in os.listdir(dir_path):sub_path = os.path.join(dir_path, file_name)if os.path.isdir(sub_path):print(count * "t" + file_name)sub_count = count + 1list_dir_content(sub_path, sub_count)if os.path.isfile(sub_path):print(count * "t" + file_name)list_dir_content("D:\test")
wd())#执行结果

test1test.xls.xlstest2test.t
D:Pythonpython_code

二.定义一个嵌套函数

外层函数打印this is outing function

内层函数打印This is inner function

def outing():print('this is outing fuction')def inner():print('this is inner fuction')inner()
outing()#执行结果
this is outing fuction
this is inner fuction

三.定义一个递归函数:打印菲波那契数列F(n)=F(n-1)+F(n-2)(n>=2,F(0)=0,F(1)=1)

def Fibonacci_series(n):a = [0]if n > 1:a = [0, 1]for i in range(n-2):a.append(a[-2] + a[-1])return a
print(Fibonacci_series(10))#执行结果
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

四.对列表进行排序

list_data = ['grape','peach','berry','pineapple','apple','strayberry','watermelon']

排序规则:按照最后一个字符进行排序,如果最后一个字符相等,按照第一个字符排序

def get_three_char(str_data):return str_data[-1], str_data[0]
list_data =  ['grape','peach','berry','pineapple','apple','strayberry','watermelon']
list_data.sort(key=get_three_char)
print(list_data)#执行结果
['apple', 'grape', 'pineapple', 'peach', 'watermelon', 'berry', 'strayberry']

五.利用map函数:计算三个列表,相同位置元素之和.

list1 = [1, 2, 3]

list2 = [4, 5, 6]

list3 = [7, 8, 9]

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]
map_obj = map(lambda x, y, z: x+y+z, list1, list2, list3)
print(list(map_obj))#执行结果
[12, 15, 18]

六.利用filter函数过滤列表中所有带a的字符串.

list_data = ['grape','what','which','you','friend','am']

list_data = ['grape', 'what', 'which', 'you', 'friend', 'am']
fil_obj = filter(lambda x: 'a' not in x, list_data)
print(list(fil_obj))#执行结果
['which', 'you', 'friend']

七.利用reduce计算1+2+3+...+100之和

from functools import reduce
red_v = reduce(lambda x, y: x+y, list(range(101)))
print(red_v)#执行结果
5050

本文发布于:2024-02-04 12:25:07,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170707181355547.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:递归   数列   思想   Python
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23