简体   繁体   中英

Understanding recursive triangle number function

I have the following recursive function that returns the nth triangle number. Could you explain how the output is, for example, 10 when I run how(4) ?

def how(n):
   if(n==1):
      return 1;
   else:
      return(n+how(n-1))
print(how(4))

The function logic is as follows - if n is 1 , return 1 . Otherwise, return n + how(n-1) . If we step through the function for how(4) , we can see how this might work:

how(4) - returns 4 + how(3)
how(3) - returns 3 + how(2)
how(2) - returns 2 + how(1)
how(1) - returns 1

Putting all this together, the following are equivalent:

how(4) - returns 4 + how(3)
how(4) - returns 4 + 3 + how(2)
how(4) - returns 4 + 3 + 2 + how(1)
how(4) - returns 4 + 3 + 2 + 1 = 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM