Python:循环与递归分别实现阶乘、斐波那契、汉诺塔

阶乘:

# 循环实现阶乘
def factorial_iteration(n):
    result = 1
    for i in range(1, n + 1):
        result *= i
    return result

# d递归实现阶乘
def factorial_recursion(n):
    if n == 1:
        return 1
    else:
        return n * factorial_recursion(n - 1)


print(factorial_recursion(3))
print(factorial_iteration(3))

斐波那契:

# 循环实现斐波那契
def fibonacci_iteration(n):
    n1 = 1
    n2 = 1
    n3 = 1
    if n < 1:  # 斐波那契数列必须从2开始
        return -1
    while (n - 2) > 0:
        n3 = n2 + n1
        n1 = n2
        n2 = n3
        n -= 1
    return n3


print(list(map(fibonacci_iteration, range(1, 12))))

# 递归实现斐波那契
def fibonacci_recursion(n):
    if n < 1:
        return -1
    if n == 1 or n == 2:
        return 1
    else:
        return fibonacci_recursion(n - 1) + fibonacci_recursion(n - 2)


print(list(map(fibonacci_recursion, range(1, 12))))

汉诺塔:

# 递归实现汉诺塔
def hanoi_recursion(n, x, y, z):
    if n == 1:
        print(x, "-->", z)
    else:
        # 将前 n-1 个物体从x移动到y上
        hanoi_recursion(n - 1, x, z, y)
        print(x, "-->", z)  # 将最底下的最后一个盘子从x移动到z上
        hanoi_recursion(n - 1, y, x, z)


hanoi_recursion(6, "x", "y", "z")

# Python 循环实现汉诺塔
class Disk:
    def __init__(self, name, disk=0):
        self.name = name
        if disk:
            self.p = [i for i in range(disk, 0, -1)]
        else:
            self.p = []

    def name(self):
        return self.name

    def get_disk_counts(self):
        return len(self.p)

    def get_top_disk(self):
        disk_counts = self.get_disk_counts()
        if disk_counts:
            return self.p[disk_counts - 1]
        return None

    def move_disk(self):
        self.p.pop()

    def add_disk(self, new_disk):
        self.p.append(new_disk)


class Hanoi:
    def __init__(self, x, y, z, disk=1):
        self.disk = disk
        self.X = Disk(x, disk)
        self.Y = Disk(y)
        self.Z = Disk(z)

    def get_move_obj(self, box):
        move_obj = box[0].get_top_disk(), box[0].name
        if move_obj[0]:
            if box[1].get_top_disk() and move_obj[0] > box[1].get_top_disk():
                move_obj = box[1].get_top_disk(), box[1].name
                box[1].move_disk()
            else:
                box[0].move_disk()
        else:
            move_obj = box[1].get_top_disk(), box[1].name
            box[1].move_disk()
        return move_obj

    def to_next(self, num, x):
        if self.disk % 2 == 0:
            sequence = {'x': 'y', 'y': 'z', 'z': 'x'}
        else:
            sequence = {'x': 'z', 'z': 'y', 'y': 'x'}
        for i in [self.X, self.Y, self.Z]:
            if i.name == sequence[x]:
                if not i.get_top_disk():
                    return i
                if num < i.get_top_disk():
                    return i
                return self.name2obj(sequence[i.name])

    def name2obj(self, x):
        for i in [self.X, self.Y, self.Z]:
            if i.name == x:
                return i

    def move(self):
        seq = [self.X, self.Y]
        while self.Z.get_disk_counts() < self.disk:
            move_obj = self.get_move_obj(seq)
            next_obj = self.to_next(move_obj[0], move_obj[1])
            next_obj.add_disk(move_obj[0])
            seq = [self.X, self.Y, self.Z]
            seq.remove(next_obj)
            print('%c --> %c' % (move_obj[1], next_obj.name))


if __name__ == '__main__':
    hanoi = Hanoi("x", "y", "z", disk=5)
    hanoi.move()

你可能感兴趣的:(python)