函數執行過程和遞歸函數練習題

函數執行過程和遞歸函數練習題

可以通過網頁工具查看代碼執行過程,鏈接如下:
函數的執行過程:
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.www58058.com/96399

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

相關推薦

  • Ipython封裝解構

    IPython Shell命令 !command 執行shell命令 !ls -l , !touch a.txt file = !ls -l | grep py 魔術方法 使用%開頭的,IPython內置的特殊方法 %magic 格式 %開頭是line magic %% 開頭是cell magic,notebook的cell %alias 定義一個系統命令的…

    2018-04-09
  • 文件IO常用操作

    io模塊 StringIO BytesIO 類
    pathlib模塊 路徑操作 3.4版本開始
    os模塊 更改權限、顯示信息 3.4版本之前路徑操作
    shuril 模塊(高級文件操作
    csv 文件
    configparser模塊 ini文件處理

    2018-05-02
  • 高階函數和裝飾器

    高階函數和裝飾器 高階函數 : 滿足以下條件之一的稱為高階函數 接受一個或多個函數作為參數 輸出一個函數 高階函數舉例: def counter(base): def inc(step=1): nonlocal base base += step return base return inc 1)自定義sort函數 def sort(itertable): …

    Python筆記 2018-04-23
  • 正則表達式

    正則表達式 分類 BRE:基本正則表達式,grep,sed,vi等軟件支持,vim有擴展 ERE:擴展正則表達式,egrep,grep -E ,sed ?r等 PCRE:幾乎所有的高級語言都是PCRE的方言或則變種, 基本語法 元字符metacharater . ?匹配除換行符外任意一個字符 [abc]字符集合,只能表示一個字符的位置,匹配所包含的任意一個字…

    Python筆記 2018-05-07
  • Python 部分知識點總結(五)

    此篇博客只是記錄第七周未掌握或不熟悉的知識點,用來加深印象。

    Python筆記 2018-04-25
欧美性久久久久