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

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

可以通过网页工具查看代码执行过程,链接如下:
函数的执行过程:
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

(0)
JacoJaco
上一篇 2018-04-16 14:50
下一篇 2018-04-16 19:53

相关推荐

  • IPython封装解构和集合

    IPython Shell命令 !command 执行shell命令 !ls -l , !touch a.txt file = !ls -l | grep py 魔术方法 使用%开头的,IPython内置的特殊方法 %magic 格式 %开头是line magic %% 开头是cell magic,notebook的cell %alias 定义一个系统命令的…

    Python笔记 2018-03-31
  • Python面向对象基础

    语言分类 面向机器 抽象成机器指令,让机器容易理解 代表:汇编语言 面向过程 按照步骤一步一步走,若出现情况A做相应的处理,若出现情况B做相应的处理 问题规模小,可以步骤化,按部就班处理 代表:C 面向对象OOP 计算机需要处理的问题的规模越来越大,需要多人、多部门协作 代表:C++、Java、Python 面向对象 一种认识世界、分析世界的方法论。将万事万…

    2018-05-06
  • Python学习第十三周总结

    网络协议和管理、http服务和Apache

    2018-06-03
  • PYTHON类型注解

    PYTHON类型注解 函数定义的弊端 Python是动态语言,变量随时可以被赋值,且能赋值为不同的类型 Python不是静态编译型语言,变量类型是在运行器决定的 动态语言很灵活,但是这种特性也是弊端 def add(x, y):return x + yprint(add(4, 5))print(add(‘hello’, ‘…

    Python笔记 2018-05-02
  • python学习总结

    内建函数、函数、插入排序、树

    2018-04-15