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 + tempresult = sum_numbers(3)print(result)
輸出:
6
補(bǔ)充拓展:python遞歸計(jì)數(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 = Falsereturn 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)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python3 json模塊之編碼解碼方法講解2. Linux刪除系統(tǒng)自帶版本Python過程詳解3. Python 制作查詢商品歷史價(jià)格的小工具4. Python 合并拼接字符串的方法5. python 使用事件對象asyncio.Event來同步協(xié)程的操作6. ASP基礎(chǔ)知識VBScript基本元素講解7. ASP.NET MVC使用jQuery ui的progressbar實(shí)現(xiàn)進(jìn)度條8. Python 利用Entrez庫篩選下載PubMed文獻(xiàn)摘要的示例9. Python sublime安裝及配置過程詳解10. Python字符串到字節(jié)的轉(zhuǎn)換。雙反斜杠問題

網(wǎng)公網(wǎng)安備