What's new

Closed pa help explain ng logic sa python recursion get_sum

Status
Not open for further replies.

bryan_16

Forum Veteran
Joined
Jul 7, 2015
Posts
3,767
Solutions
3
Reaction
1,059
Points
1,022
Hindi ko masyadong maintindihan kung pano nagana sa part na eto ng code
Python:
 return n + get_sum(n - 1)
Eto po yung buong code
Python:
def get_sum(n):    # example ang laman ng n is 5
    if n <= 1:       #dto naman is tatanungin kung yung laman ba ng n is mas maliit or equal sa 1.
        return n     # pag nag true sa condition gagawin nya eto
    return n + get_sum(n - 1) # pa explain naman po sa part na eto

num = int (input("Enter a number: "))

print("The sum of the first",str(num),"integers is",str(get_sum(num))+".")


eto po ang output
-------------------------------------
Enter a number: 5
The sum of the first 5 integers is 15.
-------------------------------------
 
Last edited:
return n+get_sum(n-1)

example: n = 5

since 5 != 1 \\ false ang return ng if so mag titrigger yung return n+get_sum(n-1)
n+get_sum(n-1) == 5 + (4) \\ 5 is from previous value of var n AND was overwritten by a new value which is 4 since get_sum(5-1=4)
'if condition' is not met since new value of n is 4 and still NOT equal to 1, thus another function call has been made this time
n+get_sum(n-1) == 9 + (3) \\ 9 is from previous return value of var n since 5+4 = 9 and 3 is from get_sum(4 - 1) in the second return and so on.
simplified equation ng code
if n =5
5+4+3+2+1 == 15
isipin mo parang while loop lang siya na '-=' ang operator.
 
Recursion will repeatedly calls itself until the condition is met (sa kaso mo, n <= 1). Tingnan mo itong modified code mo showing yung value ng number for each iteration.

Python:
x = 0
def get_sum(n):    # example ang laman ng n is 5
    global x
    x += 1
    if n <= 1:       #dto naman is tatanungin kung yung laman ba ng n is mas maliit or equal sa 1.
        print("Iteration %d -- Current value of number: %d" % (x, n))
        return n     # pag nag true sa condition gagawin nya eto
    print("Iteration %d -- Current value of number: %d" % (x, n))
    return n + get_sum(n - 1) # pa explain naman po sa part na eto

num = int (input("Enter a number: "))

print("The sum of the first",str(num),"integers is",str(get_sum(num))+".")

Eto sample run
Code:
user@debian:~/programming/python$ ./recursion.py 
Enter a number: 8
Iteration 1 -- Current value of number: 8
Iteration 2 -- Current value of number: 7
Iteration 3 -- Current value of number: 6
Iteration 4 -- Current value of number: 5
Iteration 5 -- Current value of number: 4
Iteration 6 -- Current value of number: 3
Iteration 7 -- Current value of number: 2
Iteration 8 -- Current value of number: 1
('The sum of the first', '8', 'integers is', '36.')
 
Status
Not open for further replies.

Similar threads

Back
Top