Discuss / Python / 神奇的递归....曾经用c写过汉诺塔...贼拉长一段

神奇的递归....曾经用c写过汉诺塔...贼拉长一段

Topic source

LeborYi

#1 Created at ... [Delete] [Delete and Lock User]

汉诺塔:

def hanoi(n,a,b,c):
    if n == 1:
        print(a,'---->',c)
    else:
        hanoi(n-1,a,c,b)     #首先把前n-1从a移动到b
        print(a,'---->',c)   #把n从a移动到c
        hanoi(n-1,b,a,c)     #再把n-1从b移动到c

n = int(input("请输入汉诺塔层数:"))        
print(hanoi(n,'A','B','C'))

DWLordze

#2 Created at ... [Delete] [Delete and Lock User]

最后会返回一个none,是因为没有return值吗?怎么解决好呢?

DWLordze

#3 Created at ... [Delete] [Delete and Lock User]

啊啊改成 n = int(input("请输入汉诺塔层数:"))
hanoi(n,'A','B','C') 就好了


  • 1

Reply