我就废话不多说了,直接上代码吧! def sum_numbers(num): # 1.出口 if num == 1: return 1 # 2.数组累加 temp = sum_numbers(num - 1) return num + tempresult = sum_numbers(3)print(result) 输出: 6 补充拓展:python递归
我就废话不多说了,直接上代码吧!
def sum_numbers(num): # 1.出口 if num == 1: return 1 # 2.数组累加 temp = sum_numbers(num - 1) return num + temp result = sum_numbers(3) print(result)
输出:
6
补充拓展:python递归计数及结束递归
题目:搜索旋转排序数组
class Solution: TOTAL = 0 RUN = True def search(self, nums: List[int], target: int) -> int: # 将数组一分为二,分别比头尾,尾大于头为有序,剩下的为无序 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递归调用实现数字累加的代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持易盾网络。