python recursion, example in php

rgb192
rgb192 used Ask the Experts™
on
I am having trouble understanding recursion in python because I can not relate to php (a language I am more familiar)

http://www.experts-exchange.com/Programming/Languages/Scripting/Python/Q_28489785.html
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2014

Commented:
how would you generate an Nth Fibonacci number in PHP (with or without recursion)?

Author

Commented:
how would you generate an Nth Fibonacci number in PHP (with or without recursion)?

I do not know.
Top Expert 2014
Commented:
How about calculating the factorial of a number?  This is the product of all the integers between that number and 1.
Example:
5! = 5*4*3*2*1 = 120
A PHP example of a recursive function that calculates the factorial of the number passed to it:
function fact($number) { 
    if ($number === 0) { 
        return 1; 
    } 
    else { 
        return ($number * fact($number-1)); 
    } 
}

Open in new window

Once we get down to 1 we will always be multiplying by 1, so we might be a bit more efficient if we write it as
function fact($number) { 
    if ($number < 2) { 
        return 1; 
    } 
    else { 
        return ($number * fact($number-1)); 
    } 
}

Open in new window

In both cases, we have some conditional test that stops the recursion.

Author

Commented:
thanks.

recursion example works

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial