[Tutor] Pure functions in python - need a glimpse of functional programming and recursive functions .

Alan Gauld alan.gauld at yahoo.co.uk
Fri Aug 14 04:09:44 EDT 2020


On 14/08/2020 05:42, Manprit Singh wrote:

> def fact(x): 
>      if x == 0:
>          return 1
>      else :
>          return x * fact(x-1)
> 
> def comb(n, k):
>      return fact(n) / (fact(k) * fact(n-k))

> comb(7,2)
> returns 21.0

> Just need to know if function comb is a pure function in this particular
> case or not . I have raised this question  because an external function
> fact has been called inside the function comb 3 times .

According to Wikipedia:
-----------------------
In computer programming, a pure function is a function that has the
following properties:

1)    Its return value is the same for the same arguments (no variation
with local static variables, non-local variables, mutable reference
arguments or input streams from I/O devices).
2)    Its evaluation has no side effects (no mutation of local static
variables, non-local variables, mutable reference arguments or I/O streams).
----------------------

Since you don't change state in either of your functions and there
is no random variation in the conditions the functions are both pure.

> My second question is,  i had  never seen any example of recursive
> functions in python official documentation. Is it ok to use recursive
> functions in python programming ? 

You are looking in the wrong place, a search for "recursion"
brings up 81 pages (although quite a few are the same page from
different versions!). But its mainly featured under error handling
rather than function definition because...

> Do recursive functions  take/ consume
> more or less resources in comparison to other alternatives in python ?

While not taking more resources as such, they do have a limitation
in that Python has a recursion limit (1000 by default?). This
prevents "infinite" recursion consuming all memory. But it does
mean that you should only use recursion when you know it will
terminate "fairly quickly"). Otherwise you get a RecursionError.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list