zoukankan      html  css  js  c++  java
  • 第七章 匿名函数、递归函数

    1. lambda表达式                                                                                        

    # lambda表达式
    # 匿名函数
    # 例子
    def add(a,b):
        return a+b
    add = lambda a,b: a+b
    print(add(1,2))
    # 3
    
    # 求10以内数的平方
    # 列表推导式:
    print([i**2 for i in range(3)])
    # [0, 1, 4]
    
    # 普通函数:
    def func(num):
        return num**2
    for i in map(func,range(3)):
        print(i)
    # 0
    # 1
    # 4
    # lambda表达式
    for i in map(lambda num: num**2, range(3)):print(i)
    # 0
    # 1
    # 4

    2.练习                                                                                                          

    # 1.下面程序的输出结果是:
    d = lambda p:p*2
    t = lambda p:p*3
    x = 2
    x = d(x)
    x = t(x)
    x = d(x)
    print(x)
    # 24
    
    # 2.现有两元组(('a'),('b')),(('c'),('d')),请使用python中匿名函数生成列表[{'a':'c'},{'b':'d'}]
    t1 = (('a'),('b'))
    t2 = (('c'),('d'))
    
    #答案一
    test = lambda t1,t2 :[{i:j} for i,j in zip(t1,t2)]
    print(test(t1,t2))
    # [{'a': 'c'}, {'b': 'd'}]
    #答案二
    print(list(map(lambda t:{t[0]:t[1]},zip(t1,t2))))
    # [{'a': 'c'}, {'b': 'd'}]
    #还可以这样写
    print([{i:j} for i,j in zip(t1,t2)])
    # [{'a': 'c'}, {'b': 'd'}]

     3.递归函数                                                                                              

    # 递归 就是自己调用自己
    # 递归需要有一个停止的条件
    def func():
        print(1)
        func()
    func()
    # print(1)
    # RecursionError: maximum recursion depth exceeded while calling a Python object
    # 超过了递归深度错误,没到1000 998
    
    import sys #所有跟解释器打交道的
    sys.setrecursionlimit(100000000)
    def foo(n):
        print(n)
        n += 1
        foo(n)
    foo(1)
    
    
    # 6! 6*5*4*3*2*1
    
    # def fn(n):
    #     if n == 1:return 1
    #     return  n*fn(n-1)
    # print(fn(6))
    # 720
    # 递归 就是自己调用自己
    # 递归需要有一个停止的条件
    def fn(n):
        if n == 1:return 1
        return  n*fn(n-1)
    print(fn(6))
    
    # 递:向下 归:向上
    # 分析
    def fn(6):
        return  6*fn(5)
    def fn(5):
        return  5*fn(4)
    def fn(4):
        return  4*fn(3)
    def fn(3):
        return  3*fn(2)
    def fn(2):
        return  2*fn(1)
    def fn(1):
        if n == 1:return 1
    一鼓作气,再而衰,三而竭。
  • 相关阅读:
    欧拉函数 & 【POJ】2478 Farey Sequence & 【HDU】2824 The Euler function
    【BZOJ】2982: combination(lucas定理+乘法逆元)
    【vijos】1781 同余方程(拓展欧几里得)
    Disillusioning #1 水题+原题赛(被虐瞎)
    【HDU】3622 Bomb Game(2-SAT)
    小结:双连通分量 & 强连通分量 & 割点 & 割边
    【POJ】2942 Knights of the Round Table(双连通分量)
    【POJ】1523 SPF(割点)
    【POJ】1094 Sorting It All Out(拓扑排序)
    小结:网络流
  • 原文地址:https://www.cnblogs.com/gongniue/p/8993828.html
Copyright © 2011-2022 走看看