week02斐波那契数列

1.用循环打印出斐波那契数列。

2.用递归打印出斐波那契对应的数字。

用循环制作

def rabbit2(n):
    i = 2
    x1 = 0
    x2 = 1
    x3 = 0
    a = [1]
    if n >= 2:
        while i < n + 1:
            x3 = x1 + x2
            x1 = x2
            x2 = x3
            i += 1
            a.append(x3)
        else:
            return a
    else:
        return a

n = 8
d = rabbit2(n)
print(d)


n = 1
d = rabbit2(n)
print(d)

用递归制作

第一版:重复计算版

def rabbit1(n):
    if n <= 1:
        return n
    else:
        return rabbit1(n - 1) + rabbit1(n - 2)


print('Pls print a number')
print(rabbit1(4))
print(rabbit1(12)

第二版

a = 0
rab = [0]*100


def rabbit2(n):
    global a
    a += 1

    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        b = rabbit2(n - 1)
        rab[n - 1] = b
        c = rab[n - 2]
        return b + c


print(rabbit2(100), '{} : a'.format(a))
print(rabbit2(50),'{} : a'.format(a))

用递归+数列制作,更方便:

用递归+列表制作
def rabbit1(n) :
    rab = []
    if n <= 1:
        return 1
    else:
        rab.append(1)
        rab.append(1)
        for i in range(2,n):
            rab.append(rab[i - 1] + rab[i - 2])
    return rab

print('Pls print a number')
print(rabbit3(1000))

用class解决该问题

class Rabbit:
    def __init__(self, cap):
        self.rab = [0] * cap
        self.c = 0

    def count(self, n):
        self.c += 1
        if n <= 0:
            return 0
        elif n == 1:
            return 1
        else:
            if self.rab[n - 1] > 0:
                a = self.rab[n - 1]
            else:
                a = self.count(n - 1)
                self.rab[n - 1] = a
            if self.rab[n - 2] > 0:
                b = self.rab[n - 2]
            else:
                b = self.count(n - 2)
                self.rab[n - 2] = b
            return a + b

修改后的class

class Rabbit:
    def __init__(self, cap):
        self.rab = [0] * cap
        self.c = 0

    def count(self, n):
        self.c += 1
        if n <= 0:
            return 0
        elif n == 1:
            return 1
        else:
            a = self.count(n - 1)
            self.rab[n - 1] = a
            b = self.rab[n - 2]
            return a + b

你可能感兴趣的:(week02斐波那契数列)