[Tutor] How to implement function like this?

Ricardo Aráoz ricaraoz at gmail.com
Fri Oct 26 01:26:24 CEST 2007


Kent Johnson wrote:
> Ricardo Aráoz wrote:
>> 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]
> 
>> def funcA(tArray) :
>>     a = [2,3,4]
>>     L = min(len(tArray), 3)
>>     return tuple(i for n, i in enumerate(a) if n <
>> L)+tuple(funcB(len(a)-L))
> 
> tuple(i for n, i in enumerate(a) if n < L) can be written
> tuple(a[:L])

Doh... Of course! Your code is much nicer.

> 
> funcB(len(a)-L) does not do what the OP requested. For example if len(a)
> is 10, L will be 3 and you will call funcB(7).
> 

Don't get it. The 3 is because the len(a) is 3, notice that a is hard
coded and not a parameter. If you change 'a' then you should change the
code accordingly. Anyway the confusion is the mixing of len(a) and 3 in
the same code, it should probably be either 3 or len(a) all along, but
that should be asked to the OP.
Let's say we decide to use len(a), then the code would end up like :

def funcA(tArray) :
    a = [2,3,4]
    L = min(len(tArray), len(a))
    return tuple(a[:L]) + tuple(funcB(len(a) - L))

Too tired right now to check if it's ok.

Cheers.


More information about the Tutor mailing list