Python: Recursive function to find the largest number in the list

前端 未结 10 647
长情又很酷
长情又很酷 2020-12-10 21:04

I\'m trying to do a lab work from the textbook Zelle Python Programming

The question asked me to \"write and test a recursive function max() to find the

10条回答
  •  既然无缘
    2020-12-10 21:18

    def find_max(arr):
      """find maximum number in array by recursion"""
      if arr == []: # if its an empty array
        return 0
      if len(arr) == 1: # if array has only one element
        return arr[0]
      else: # get max of first item compared to other items recursively
        return max(arr[0], find_max(arr[1:])) # 1: means all other excluding 0th element
    
    def main():
      print(find_max([2,3,5,6,7,1])) # will print max - 7
    
    if __name__ == "__main__":
      main()
    

提交回复
热议问题