Pythonic Code In Several Lines

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Pythonic Code In Several Lines相关的知识,希望对你有一定的参考价值。

  1. Fibonacci Series

#1
def Fib(n):
    if n == 1 or n == 2:
        return 1;
    else:
        return Fib(n - 1) + Fib(n - 2)
#2
def Fib(n):
    return 1 and n <= 2 or Fib(n - 1) + Fib(n - 2)
#3
Fib = lambda n: 1 if n <= 2 else Fib(n - 1) + Fib(n - 2)

#4
def Fib(n):
    x, y = 0, 1
    while(n):
        x, y, n = y, x + y, n - 1
    return x
#5
Fib = lambda n, x = 0, y = 1 : x if not n else Fib(n - 1, y, x + y)
#6
def Fib(n):
    def Fib_iter(n, x, y):
        if n == 0: 
            return x 
        else: 
            return Fib_iter(n - 1, y, x + y)
    return Fib_iter(n, 0, 1)
#7
def fib(n):
    def m1(a,b):
        m=[[],[]]
        m[0].append(a[0][0]*b[0][0]+a[0][1]*b[1][0])
        m[0].append(a[0][0]*b[0][1]+a[0][1]*b[1][1])
        m[1].append(a[1][0]*b[0][0]+a[1][1]*b[1][0])
        m[1].append(a[1][0]*b[1][0]+a[1][1]*b[1][1])
        return m
    def m2(a,b):
        m=[]
        m.append(a[0][0]*b[0][0]+a[0][1]*b[1][0])
        m.append(a[1][0]*b[0][0]+a[1][1]*b[1][0])
        return m
    return m2(reduce(m1,[[[0,1],[1,1]] for i in range(n)]),[[0],[1]])[0]

 

以上是关于Pythonic Code In Several Lines的主要内容,如果未能解决你的问题,请参考以下文章