recursing question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • python101
    New Member
    • Sep 2007
    • 90

    recursing question

    I have the code
    [code=python]
    def calculation(n):
    print 'n =', n
    if n<=1:
    return n
    if n%2==0:
    print 'Even'
    return calculation(n-1) + calculation(n-2) + 1
    else:
    print 'Odd'
    return n

    print calculation(4)

    [/code]

    the result is
    [code=python]
    n = 4
    Even
    n = 3
    Odd
    n = 2
    Even
    n = 1
    n = 0
    6
    [/code]
    Can anyone explain why I get this result?

    And provide some other similar examples, so I can get practiced with this kind of problem?
  • ilikepython
    Recognized Expert Contributor
    • Feb 2007
    • 844

    #2
    Originally posted by python101
    I have the code
    [code=python]
    def calculation(n):
    print 'n =', n
    if n<=1:
    return n
    if n%2==0:
    print 'Even'
    return calculation(n-1) + calculation(n-2) + 1
    else:
    print 'Odd'
    return n

    print calculation(4)

    [/code]

    the result is
    [code=python]
    n = 4
    Even
    n = 3
    Odd
    n = 2
    Even
    n = 1
    n = 0
    6
    [/code]
    Can anyone explain why I get this result?

    And provide some other similar examples, so I can get practiced with this kind of problem?
    What result did you expect to get?
    Last edited by ilikepython; Dec 22 '07, 10:06 PM. Reason: typo

    Comment

    • elcron
      New Member
      • Sep 2007
      • 43

      #3
      Originally posted by python101
      I have the code
      [code=python]
      def calculation(n):
      print 'n =', n
      if n<=1:
      return n
      if n%2==0:
      print 'Even'
      return calculation(n-1) + calculation(n-2) + 1
      else:
      print 'Odd'
      return n

      print calculation(4)

      [/code]

      the result is
      [code=python]
      n = 4
      Even
      n = 3
      Odd
      n = 2
      Even
      n = 1
      n = 0
      6
      [/code]
      Can anyone explain why I get this result?

      And provide some other similar examples, so I can get practiced with this kind of problem?
      This will help make it more visible.
      [code=python]
      def calculation(n, nesting=0):
      print ' '*nesting, 'n =', n
      if n<=1:
      return n
      if n%2==0:
      print ' '*(nesting + 1), 'Even'
      return calculation(n-1, nesting+1) + calculation(n-2, nesting+1) + 1
      else:
      print ' '*(nesting + 1), 'Odd'
      return n


      print calculation(4)

      """
      output
      n = 4
      Even
      n = 3
      Odd
      n = 2
      Even
      n = 1
      n = 0
      6
      """
      [/code]

      Comment

      Working...