递归访问目录,打印斐波那契数列,高阶函数


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

def listdir(path, count=0):
    list_dir = os.listdir(path)
    for i in list_dir:
        path1 = os.path.join(path + "/", i)
        if os.path.isdir(path1):
            print(count * "    ", i)
            count1 = count + 1
            listdir(path1, count1)
        else:
            print(count * '    ', i)


listdir('E:text1')

2.定义一个嵌套函数,外层函数打印this is outing function,内层函数功能:打印This is inner function

def outer():
    print('this is outing function')

    def inner():
        print('this is inner function')

    return inner


outer()()

3.定义一个递归函数:打印斐波那契数列

F[n]=F[n-1]+F[n-2] (n>=2,F[0]=0,F[1]=1)

'''
1 1 2 3 5 8 13
1 2 3 4 5 6 7
f(7) = f(6) + f(5)
f(n) = f(n-1) + f(n-2)
'''


def print_info(n):
    if n == 1 or n == 2:
        return 1
    else:
        return print_info(n - 1) + print_info(n - 2)


sum1 = print_info(7)
print(sum1)

4.对列表进行排序:

list_data = [“grape”, “peach”, “berry”, “pineapple”, “apple”, “strayberry”, “watermelon”]
排序规则:按照最后一个字符进行排序,如果最后一个字符相等,按照第一个字符排序

def sort(string):
    return string[-1], string[0]


list_data = ["grape", "peach", "berry", "pineapple", "apple", "strawberry", "watermelon"]
list_data1 = sorted(list_data, key=sort)
print(list_data1)

5.利用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]
print(list(map(lambda x, y, z: x + y + z, list1, list2, list3)))

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

list_data = [“grape”, “what”, “which”, “you”, “friend”, “am”]

list_data = ["grape", "what", "which", "you", "friend", "am"]
print(list(filter(lambda x: 'a' not in x, list_data)))

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

print(reduce(lambda x, y: x + y, range(1, 101)))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值