python之函数(28)(动态补充)

# 函数类型参数
# 联想到python中的装饰器

import datetime


def timer(t, start, finished):
    t_start = datetime.datetime.now()
    if start:
        start()
    while True:
        t_end = datetime.datetime.now()
        cost_t = t_end - t_start
        if cost_t.seconds >= t:
            break
        if finished:
            finished()


def f():
    i = int(input("请输入数字:"))
    print(i)


def s():
    print("稍等一哈")


timer(2, s, f)
# 闭包

def counting(count):
    def fn():
        nonlocal count
        count -= 1
        if count < 0:
            return
        return count
    return fn
a = counting(5)
b = counting(6)

# fn()运行时依赖count,系统会把函数和变量(依赖的环境)一起打包放在一起
# 匿名函数
# 通过使用lambda实现

def f(x):
    return x * 2


a = lambda x: x * 2 # 后面的表达式不能换行


def map_list(fn,l):
    result = []
    for item in l:
        i = fn(item)
        result.append(i)
    return result


l = [1,2,3,4]

l = map_list(lambda x: x ** 2,l)
print(l)
# 递归写法
# def f(i):
#     if i <= 1:
#         return 1
#     else:
#         return f(i-1) * i


# lambda i: 1 if i <= 1 else format(i -1) * i

# 普通写法
# def f1(num):
#     result = 1
#     for i in range(num):
#         result *= i + 1
#     return result

# r = f(999)
# print(r)

# 递归容易出现:RecursionError: maximum recursion depth exceeded in comparison ;
# Python(或者更确切地说,CPython实现)没有优化尾递归,而肆无忌惮的递归会导致堆栈溢出 ;
# 可以将递归限制更改为sys.setrecursionlimit但是这样做是危险的-标准限制有点保守,但是Python堆栈框架可能相当大;
# Python不是一种函数式语言,尾递归不是一种特别有效的技术。如果可能的话,迭代重写算法通常是一个更好的主意 ;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值