[Tutor] How to implement function like this?

Kent Johnson kent37 at tds.net
Tue Oct 23 13:45:03 CEST 2007

Yinghe Chen wrote:
> Hello gurus,
> I have a question, a function like below, it is implemented by me, :)
> 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]
> The return of funcA is always 3 values, but depending on the length of 
> tarray, I need to return different values accordingly.  if tarray lenght 
> is 2, I need to get another one value from funcB, if tarray length is 0, 
> I need to get all three values from funcB.

I think this works; not sure if it is better. The list() calls are not 
needed if tarray and the result of funcB are already lists; the tuple 
calls may not be needed either:

def funcA(tarray):
   a = [2,3,4]
   if len(tarray) >=3:
     return tuple(a)
   result = list(tarray) + list(funcB(3-len(tarray)))
   return tuple(result[:3])


More information about the Tutor mailing list