Performing Essential Data Manipulations Using Python
107
def factorial(n):
print("factorial called with n = ", str(n))
result = 1
while n > 1:
result = result * n
n = n - 1
print("Current value of n is ", str(n))
print("Ending condition met.")
return result
print(factorial(5))
factorial called with n = 5
Current value of n is 4
Current value of n is 3
Current value of n is 2
Current value of n is 1
Ending condition met.
120
The basic flow of this function is the same as the recursive function. A
while
loop
replaces the recursive call, but you still need to check for the same condition and
continue looping until the data meets the condition. The result is the same. How-
ever, replacing recursion with iteration is nontrivial in some cases, as explored in
the example at
http://blog.moertel.com/posts/2013-06-03-recursion-to-
iteration-3.html
.
Do'stlaringiz bilan baham: |