Python遞歸調(diào)用實(shí)現(xiàn)數(shù)字累加的代碼
我就廢話不多說了,直接上代碼吧!
def sum_numbers(num):
# 1.出口
if num == 1:
return 1
# 2.數(shù)組累加
temp = sum_numbers(num - 1)
return num + temp
result = sum_numbers(3)
print(result)
輸出:
6
補(bǔ)充拓展:python遞歸計數(shù)及結(jié)束遞歸
題目:搜索旋轉(zhuǎn)排序數(shù)組

class Solution:
TOTAL = 0
RUN = True
def search(self, nums: List[int], target: int) -> int:
# 將數(shù)組一分為二,分別比頭尾,尾大于頭為有序,剩下的為無序
i, j = 0, len(nums) - 1
res = -1
if nums and self.RUN:
in_middle = (j + i) // 2
list1 = nums[:in_middle + 1]
list2 = nums[in_middle + 1:]
if nums[in_middle] >= nums[i]:
res = self.binarySearch(list1, target)
if res == -1:
self.TOTAL += in_middle + 1
self.search(list2, target)
else:
self.TOTAL += res
else:
res = self.binarySearch(list2, target)
if res == -1:
self.search(list1, target)
else:
self.TOTAL += in_middle + 1 + res
if not self.RUN:
return self.TOTAL
return res
def binarySearch(self, nums, target):
""" 二分查找 """
i, j = 0, len(nums) - 1
while i <= j:
in_middle = (j + i) // 2
if nums[in_middle] == target:
# print(nums, TOTAL)
self.RUN = False
return in_middle
elif nums[in_middle] < target:
i = in_middle + 1
else:
j = in_middle - 1
return -1
以上這篇Python遞歸調(diào)用實(shí)現(xiàn)數(shù)字累加的代碼就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python實(shí)現(xiàn)半自動化發(fā)送微信信息
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)半自動化發(fā)送微信信息,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08
在python中使用pymysql往mysql數(shù)據(jù)庫中插入(insert)數(shù)據(jù)實(shí)例
今天小編就為大家分享一篇在python中使用pymysql往mysql數(shù)據(jù)庫中插入(insert)數(shù)據(jù)實(shí)例。具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
python神經(jīng)網(wǎng)絡(luò)Keras實(shí)現(xiàn)LSTM及其參數(shù)量詳解
這篇文章主要為大家介紹了python神經(jīng)網(wǎng)絡(luò)Keras實(shí)現(xiàn)LSTM及其參數(shù)量詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
jupyter notebook 中輸出pyecharts圖實(shí)例
這篇文章主要介紹了jupyter notebook 中輸出pyecharts圖實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06
Python實(shí)現(xiàn)生命游戲的示例代碼(tkinter版)
生命游戲是由劍橋大學(xué)約翰·何頓·康威設(shè)計的計算機(jī)程序,一時吸引了各行各業(yè)一大批人的興趣。本文將用Python實(shí)現(xiàn)這一游戲,感興趣的可以嘗試一下2022-08-08
python網(wǎng)絡(luò)爬蟲 Scrapy中selenium用法詳解
這篇文章主要介紹了python網(wǎng)絡(luò)爬蟲 Scrapy中selenium用法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值2019-09-09

