首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何解释到达第n层的计数方式的代码?

如何解释到达第n层的计数方式的代码?
EN

Stack Overflow用户
提问于 2019-09-28 16:38:46
回答 1查看 55关注 0票数 0

我试图从极客健忘者那里解读这段代码:

代码语言:javascript
复制
def fib(n): 
    if n <= 1: 
        return n 
    return fib(n-1) + fib(n-2) 

def countWays(s): 
    return fib(s + 1) 

s = 4
print "Number of ways = ", 
print countWays(s) 

当我把数字替换到函数中时,我似乎无法得到正确的答案。以下是我的思考过程:

代码语言:javascript
复制
def countWays(s): 
    return fib(4 + 1) #5

#this goes into fib(n). 5 is not less than or equal to n so I skip to the else statement:

fib(5-1) + fib(5-2) 

#fib(4) + fib(3) since these are still not less than or equal to n I input 
#them into the function again.

 fib(4-1) + fib(3-2) 

#fib(3) + fib(1) now that one of the n is less than or equal to n, 
#I return n and get 4 (3+1). The answer is supposed to be 5.
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-28 17:11:19

就像这样检查一下:

代码语言:javascript
复制
# Python 3
def fib(n): 
    print(f'Fib: {n}')
    if n <= 1:
        print('End')
        return n
    else:
        print(f'Send: {n-1} and {n-2}')
    return fib(n-1) + fib(n-2) 

def countWays(s): 
    return fib(s + 1) 

s = 4
print("Number of ways = ")
print(countWays(s))

结果

代码语言:javascript
复制
Fib: 5           # A
Send: 4 and 3    # A.B and A.C
Fib: 4           # A.B
Send: 3 and 2    # A.B.1 and A.B.2
Fib: 3           # A.B.1
Send: 2 and 1    # A.B.1.1 and A.B.1.2
Fib: 2           # A.B.1.1
Send: 1 and 0    # A.B.1.1.1 and A.B.1.1.2
Fib: 1           # A.B.1.1.1
End              # (END) A.B.1.1.1       -> 1
Fib: 0           # A.B.1.1.2
End              # (END) A.B.1.1.2       -> 0
Fib: 1           # A.B.1.2
End              # (END) A.B.1.2         -> 1
Fib: 2           # A.B.2
Send: 1 and 0    # A.B.2.1 and A.B.2.2
Fib: 1           # A.B.2.1
End              # (END) A.B.2.1         -> 1
Fib: 0           # A.B.2.2
End              # (END) A.B.2.2         -> 0
Fib: 3           # A.C
Send: 2 and 1    # A.C.1 and A.C.2
Fib: 2           # A.C.1
Send: 1 and 0    # A.C.1.1 and A.C.1.2
Fib: 1           # A.C.1.1
End              # (END) A.C.1.1         -> 1
Fib: 0           # A.C.1.2
End              # (END) A.C.1.2         -> 0
Fib: 1           # A.C.2
End              # (END) A.C.2           -> 1
5                                     # 1 + 0 + 1 + 1 + 0 + 1 + 0 + 1

现在替代

代码语言:javascript
复制
>>> print(fib(5))
Fib: 5
Send: 4 and 3
Fib: 4
...
Fib: 1
End
5

同样的结果。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58148347

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档