banner ad

Python Recursion Function

| January 21, 2013 | 0 Comments
0 Flares 0 Flares ×

Python support recursion, which means that functions can call themselves within their definitions. Recursion function definition would be

def recursion():
    return recursion()

The factorial of n is defined as n!=n*(n-1)*(n-2)…2*1. If efficiency is not a concern, computing factorials is trivial from an algorithmic point of view: successively multiplying a variable initialized to 1 by the integers 2 up to n (if any) will compute n!, provided the result fits in the variable. In functional languages, the recursive definition is often implemented directly to illustrate recursive functions. How do you calculate it? You could always use a loop:

def factorial(n):
    result = 1
    for i in range(1,n):
        result *=i
        return result

or recursion function:

def factorial(n):
    if n == 0 or n == 1: return 1
    else: return (n * factorial(n - 1))

let’s start with a other recursion function: power(x,n) (x to the power of n) is the number x
multiplied by itself n-1 times (so that x is used as a factor n times). So power(4,3) is 2 multiplied
with itself twice, or 4*4*4= 64

def power(x, n):
    if n == 0:
        return 1
    else:
        return x * power(x, n-1)
Download PDF
0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Reddit 0 StumbleUpon 0 0 Flares ×

Tags: , ,

Category: Function

About the Author ()

My name is John Link.I am 26 years old. My major is Computer science and technology. I am a junior programmer with Python.

Leave a Reply

Your email address will not be published. Required fields are marked *

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Reddit 0 StumbleUpon 0 0 Flares ×