遞迴練習答案

2021-09-06 16:12:32 字數 1187 閱讀 6541

《演算法**》4.1/4.2/4.3

# 請編寫前述sum函式的**:

def sum(list):

if list == :

return 0

return list[0] + sum(list[1:])

print(sum([4, 5, 6, 7]))

# 編寫乙個遞迴函式來計算列表包含的元素數

def count(list):

if list == :

return 0

return 1 + count(list[1:])

print(count([4, 5, 6, 7]))

# 找出列表中最大的數字

def max(list):

if len(list) == 0:

return none

if len(list) == 1:

return list[0]

if len(list) == 2:

return list[0] if list[0] > list[1] else list[1]

sub_max = max(list[1:])

return list[0] if list[0] > sub_max else sub_max

print(max([4, 5, 6, 7]))

print(max())

print(max([1]))

# 如果沒有len(list)為0或者1的保護**,如上會報錯

# recursionerror: maximum recursion depth exceeded in comparison

def max2(list):

if len(list) == 0:

return none

if len(list) == 1:

return list[0]

if len(list) == 2:

if list[0] > list[1]:

return list[0]

return list[1]

sub_max = max(list[1:])

if list[0] > sub_max:

return list[0]

return sub_max

print(max2([3, 4, 5, 6]))

JS 練習答案

目錄 01 動態給頁面上新增div.html 02 刪除替換轉殖標籤.html 03 全選全不選反選.html 04 新聞字型.html 05 增刪.html 06 動態生成 html 07 隔行變色.html 08 左到右右到左.html 09 二級聯動.html 10 註冊頁面.html yyy...

sqlzoo練習答案

這個教程介紹sql語言。我們會使用select語句。我們會使用world name continent area population gdp afghanistan asia 652230 25500100 20343000000 albania europe 28748 2831741 1296...

ArrayList練習(帶答案)

問題描述 將自定義物件作為元素存到arraylist集合中,並去除重複元素。比如 存人物件。同姓名同年齡,視為同乙個人。為重複元素。思路 1,對人描述,將資料封裝進人物件。2,定義容器,將人存入。3,取出。list集合判斷元素是否相同,依據是元素的equals方法。知識點一 remove和add方法...