1。寫一個遞回函式,串列輸出累計最小值。
例如:m=[2,3,2,1,3] 最后的回傳值為[2,2,2,1,1]
2。怎么用遞回函式寫二分法來找出串列中元素的位置?
感激不盡!!!
uj5u.com熱心網友回復:
第一題list_in = [2, 3, 2, 1, 3]
list_out = []
dd = float("inf")
def get_min(list_in, list_out, list_min):
mm = min(list_in[0], list_min)
list_out.append(mm)
print(list_out)
if len(list_in)>1:
get_min(list_in[1:], list_out, mm)
get_min(list_in, list_out, dd)
uj5u.com熱心網友回復:
第二題list_in = [2, 4, 6, 8, 10]
value = 5
def binary_search(list_in, index_low, index_high, value):
if index_low == index_high:
return index_low if list_in[index_low] == value else -1
index_mid = int((index_low+index_high)/2)
if list_in[index_mid] == value:#等于中間值
return index_mid
elif list_in[index_mid] < value:#大于中間值
return binary_search(list_in, index_mid+1, index_high, value)
else:#小于中間值
return binary_search(list_in, index_low, index_mid, value)
print(binary_search(list_in, 0, len(list_in)-1, value))
輸出
-1
[Finished in 0.1s]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/119302.html
上一篇:Python解方程
下一篇:Python爬蟲
