GeorgeDI

Recursion

Oct 22nd, 2022
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. def alt_tri_recursion(k):
  2. if(k > 0) :
  3. result = k + alt_tri_recursion(k - 1)
  4. print(result)
  5. else:
  6. result = 0
  7. return result
  8.  
  9. alt_tri_recursion(6)
  10.  
  11.  
  12.  
  13.  
  14.  
  15. '''https://www.quora.com/Can-you-explain-me-this-def-tri_recursion-k-if-k-0-result-k-tri_recursion-k-1-print-result-else-result-0-return-result-print-n-nRecursion-Example-Results-tri_recursion-6'''
  16.  
  17. '''def tri_recursion(k):
  18. if(k > 0):
  19. result = k + tri_recursion(k - 1)
  20. print(result)
  21. else:
  22. result = 0
  23. return result
  24.  
  25. print("\n\nRecursion Example Results")
  26. tri_recursion(4)'''
  27.  
  28. '''
  29. Profile photo for David Lewis
  30. David Lewis
  31. ·
  32. Follow
  33. Former Python Developer (1999–2014)2y
  34. def tri_recursion(k):
  35. if (k > 0):
  36. result = k + tri_recursion (k - 1)
  37. print (result)
  38. else:
  39. result = 0
  40. return result
  41.  
  42. print ("\n\nRecursion Example Results")
  43. tri_recursion(6)
  44. I had to deduce that the return on line 7 wasn’t in the else clause. The code doesn’t work otherwise. There must be some way to post python code so we don’t have to guess what the structure is.
  45.  
  46. The function returns the sum of the numbers up to and including it’s argument. In the case of 6 it returns 6+5+4+3+2+1+0. The first print you see is 1+0. The next is 2+1+0. And so on up to 6+5+4+3+2+1+0.
  47.  
  48. The output if you paste this into the interpreter is:
  49.  
  50. Recursion Example Results
  51. >>> tri_recursion(6)
  52. 1
  53. 3
  54. 6
  55. 10
  56. 15
  57. 21
  58. 21
  59. It’s a little confusing because you have output from prints mixed with outputs from the paste. That’s why you see the “>>> tri_recusion(6)” and a second “21” (which is the result of calling tri_recussion with 6).
  60.  
  61. If you run it from a file, you get:
  62.  
  63. Recursion Example Results
  64. 1
  65. 3
  66. 6
  67. 10
  68. 15
  69. 21
  70. This is (in order) the sequence of events and the indent shows in what level of recursion where each thing happens. If you study this, you should understand what’s going on.
  71.  
  72. result = 6 + 15
  73. result = 5 + 10
  74. result = 4 + 6
  75. result = 3 + 3
  76. result = 2 + 1
  77. result = 1 + 0
  78. print 1
  79. print 3
  80. print 6
  81. print 10
  82. print 15
  83. print 21
  84. Hope this helps.'''
Tags: recursion
Advertisement
Add Comment
Please, Sign In to add comment