>  기사  >  백엔드 개발  >  Python에서 재귀를 사용하여 목록 정수의 합계를 계산하는 방법은 무엇입니까?

Python에서 재귀를 사용하여 목록 정수의 합계를 계산하는 방법은 무엇입니까?

Patricia Arquette
Patricia Arquette원래의
2024-10-21 12:02:33685검색

How to Calculate Sum of List Integers Using Recursion in Python?

Python의 재귀 이해: 목록 정수 합산

재귀는 문제의 작은 인스턴스를 해결하기 위해 함수가 반복적으로 자신을 호출하는 프로그래밍 기술입니다. 기본 조건에 도달할 때까지. Python에서는 목록 정수의 합 계산을 포함하여 다양한 작업에 재귀를 적용할 수 있습니다.

재귀 함수: listSum

목록을 취하는 재귀 함수 listSum을 정의하려면 정수로 구성하고 그 합계를 반환하면 문제를 다음과 같이 분류할 수 있습니다.

  • 기본 조건: 목록이 비어 있는 경우(목록 == []) 합계는 다음과 같습니다. 0.
  • 재귀 단계: 목록이 비어 있지 않으면 합계는 첫 번째 요소(list[0])에 나머지 요소의 합계(listSum(list[1: ])).

간단 버전:

<code class="python">def listSum(ls):
    # Base condition
    if not ls:
        return 0

    # First element + result of calling `listsum` with rest of the elements
    return ls[0] + listSum(ls[1:])</code>

테일 호출 재귀:

효율성 향상 , 현재 합계를 함수 매개변수에 전달할 수 있습니다:

<code class="python">def listSum(ls, result):
    # Base condition
    if not ls:
        return result

    # Call with next index and add the current element to result
    return listSum(ls[1:], result + ls[0])</code>

인덱스 버전 전달:

중간 목록 생성을 피하기 위해 다음 인덱스를 전달할 수 있습니다. 현재 요소:

<code class="python">def listSum(ls, index, result):
    # Base condition
    if index == len(ls):
        return result

    # Call with next index and add the current element to result
    return listSum(ls, index + 1, result + ls[index])</code>

내부 함수 버전:

코드를 단순화하기 위해 재귀 내부 함수를 정의할 수 있습니다:

<code class="python">def listSum(ls):

    def recursion(index, result):
        # Base condition
        if index == len(ls):
            return result

        # Call with next index and add the current element to result
        return recursion(index + 1, result + ls[index])

    return recursion(0, 0)</code>

기본 매개변수 버전:

기본 매개변수를 사용하면 더욱 단순화할 수 있습니다.

<code class="python">def listSum(ls, index=0, result=0):
    # Base condition
    if index == len(ls):
        return result

    # Call with next index and add the current element to result
    return listSum(ls, index + 1, result + ls[index])</code>

위 내용은 Python에서 재귀를 사용하여 목록 정수의 합계를 계산하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.