遞迴小練習

2021-10-08 11:42:38 字數 3709 閱讀 6401

演算法入門,看到遞迴,做了幾個小練習。

1.1找準基線條件(停止遞迴)

1.2明確函式功能,知道寫的函式究竟是幹什麼的

def

get_max_value

(lst):if

len(lst)==2

:#基線條件

return lst[0]

if lst[0]

>= lst[1]

else lst[1]

return lst[0]

if lst[0]

>get_max_value(lst[1:

])else get_max_value(lst[1:

])if __name__ ==

"__main__"

: li =[8

,4,5

,7,1

,3,6

,2]print

("max value:"

, get_max_value(li)

)

max value: 8

process finished with exit code 0

def

sum_list

(lst):if

len(lst)==0

:return

0return lst[0]

+ sum_list(lst[1:

])if __name__ ==

"__main__"

: li =[8

,4,5

,7,1

,3,6

,2]print

('the result of sum:'

)print

(sum_list(li)

)

the result of sum:

36process finished with exit code 0

def

quick_sort

(lst):if

len(lst)

<=1:

return lst

# base_value = lst[-1]#選取最後乙個元素作為基準值

mid_index =

int(

len(lst)/2

) base_value = lst[mid_index]

#選取中間值作為基準值

rest = lst[

0:mid_index]

+ lst[mid_index+1:

] smaller =

[i for i in rest if i < base_value]

larger =

[j for j in rest if j >= base_value]

return quick_sort(smaller)

+[base_value]

+ quick_sort(larger)

if __name__ ==

"__main__"

: li =[8

,4,5

,7,1

,3,6

,2]print

("排序後的佇列:"

, quick_sort(li)

)

排序後的佇列: [1, 2, 3, 4, 5, 6, 7, 8]

process finished with exit code 0

def

merge_sort

(lst):if

len(lst)

<2:

return lst

#分的過程

mid_index =

int(

len(lst)/2

) left = lst[

:mid_index]

right = lst[mid_index:

] left = merge_sort(left)

right = merge_sort(right)

#治的過程

result =

while left and right:

if left[0]

<= right[0]

:0))

else:0

))if left:

result += left

if right:

result += right

return result

if __name__ ==

"__main__"

: li =[8

,4,5

,7,1

,3,6

,2]print

("排序後的佇列:"

, merge_sort(li)

)

排序後的佇列: [1, 2, 3, 4, 5, 6, 7, 8]

process finished with exit code 0

def

er_fen

(min_index, max_index, target)

: mid_index =

int(

(min_index+max_index)/2

)if a[mid_index]

== target:

return mid_index

if a[mid_index]

>target:

return er_fen(min_index, mid_index, target)

if a[mid_index]

return er_fen(mid_index, max_index, target)

if __name__ ==

"__main__"

: a =[1

,3,6

,7,9

,10,100

,1000

,2000

,100000

]print

(er_fen(0,

len(a)-1

,1000

))

7

process finished with exit code 0

def

max_length

(a, b)

:if a % b ==0:

return b

else

:return max_length(b, a-

int(a/b)

*b)if __name__ ==

"__main__"

:print

('最大邊長:'

)print

(max_length(

1680

,640

))

最大邊長:

80process finished with exit code 0

遞迴函式小練習

define crt secure no warnings 1 includeint fibonacci1 int n else int fibonacci int n else return a3 int main define crt secure no warnings 1 includein...

python 兩個小練習理解遞迴函式

遞迴是解決問題的一種方式,它和迴圈很像 它的整體思想是,將乙個大問題分解為乙個個的小問題,直到問題無法分解時,再去解決問題 遞迴式函式的兩個要件 1.基線條件 2.遞迴條件 例題 編寫求n 的遞迴函式 分析 n 等於1 2 n 1 n n 也等於n n 1 比如 10 10 9 9 9 8 8 8 ...

基礎 遞迴練習

1 有乙個農場在第一年的時候買了一頭剛出生牛,這頭牛在第四年的時候就能生一頭小牛,以後每年這頭牛就會生一頭小牛。這些小牛成長到第四牛又會生小牛,以後每年同樣會生一頭牛,假設牛不死,如此反覆。請問50年後,這個農場會有多少頭牛?首先定義最終終止條件f 4 1 然後定義遞迴公式中f n f n 1 f ...