[Tutor] How to implement function like this?

Alan Gauld alan.gauld at btinternet.com
Tue Oct 23 12:55:53 CEST 2007


"Yinghe Chen" <chenyinghe at gmail.com> wrote

> def funcA(tarray):
>       a = [2,3,4]
>        if len(tarray) >=3:
>             return a[0],a[1], a[2]
>        elif len(tarray) == 2:
>            return a[0],a[1], funcB(1)[0]
>        elif len(tarray) == 1:
>           return a[0], funcB(2)[0], funcB(2)[1]
>        else:
>            return funcB(3)[0], funcB(3)[1], funcB(3)[2]
> 
> 
> Is there a brief way to achieve it?

It looks fairly brief to me. There are a couple of things I 
might consider changing.

def funcA(tArray, defs = (2,3,4), func = funcB):
     if len(tArray) >= 3:
         return defs
     elif len(tArray) == 2:
          return defs[0],defs[1], func(2)[1]
     elif....

By making defs a tuple you can return it directly and by 
making it a defaulted parameter you can change the 
values if needed without changing the funcA code.
Similarly by making funcB a default parameter you 
have the flexibility to change the algorithm used 
without changing funcA. But because they are default 
parameters you can still call it with just tArray as 
an argument.

A small change but may significantly improve the 
flexibility and possible reuse capability of funcA

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list