函数执行过程和递归函数练习题

函数执行过程和递归函数练习题

可以通过网页工具查看代码执行过程,链接如下:
函数的执行过程:
def foo1(b,b1=3):
print(“foo1 called”,b,b1)
return 1
def foo2(c):
print(“foo2 called”,c)
return foo3(c)
def foo3(d):
print(“foo3 called”,d)
return 3
def main():
print(“main called”)
foo1(100,101)
foo2(200)
return (“main ending”, foo1(1) + foo2(2) + foo3(3))
print(main())
斐波那契数列:
函数嵌套形式:{{{}{}}{{}{}}}
#F(0)=0, F(1)=1, F(n)=F(n-1) + F(n-2)
def fib(n):
return 1 if n < 2 else fib(n-1) + fib(n-2)
fib(5)
#F(0)=0, F(1)=1, F(n)=F(n-1) + F(n-2)
pre = 0
cur = 1
print(pre,cur,end=’ ‘)
def fib(n,pre = 0, cur = 1):
pre, cur = cur, pre + cur
print(cur, end = ‘ ‘)
if n == 2:
return
fib(n-1,pre,cur)
fib(5)
阶乘:
函数嵌套形式{{{{}}}}
def fac(n):
if n == 1:
return 1
return n * fac(n-1)
fac(5)
def fac(n, m = 1):
if n == 1:
return m
m *= n
return fac(n-1,m)
fac(5)
逆序打印数字:
将一个数字逆序放入列表中,例如1234 => [4,3,2,1]
nums = 12345789
def revert(nums, lst=[]):
x,y = divmod(nums, 10)
lst.append(y)
if x == 0:
return lst
return revert(x)
print(revert(nums))
strsample = “abcdef”
# nums = str(nums)
def revert(strsample, lst=[]):
if len(strsample) == 0:
return lst
lst.append(strsample[-1])
return revert(strsample[:len(strsample)-1],lst)
print(revert(strsample))
clipboard
解答:
y = x/2 – 1
def peach(n, x = 1):
if n == 1:
return x
x = 2 * (x + 1)
return peach(n-1, x)
print(peach(10))
def peach(days=1):
if days == 10:
return 1
num = (peach(days+1) + 1)*2
return num
print(peach())
def peach(days=10):
if days == 1:
return 1
return (peach(days-1) + 1)*2
print(peach())

本文来自投稿,不代表Linux运维部落立场,如若转载,请注明出处:http://www.178linux.com/96399

联系我们

400-080-6560

在线咨询

工作时间:周一至周五,9:30-18:30,节假日同时也值班

QR code