Search the difference: Why this function defenition does'nt work?
husam
h.jehadalwan at student.kun.nl
Sun Dec 23 11:47:14 EST 2001
Roman Suzi wrote:
> On Sun, 23 Dec 2001, husam wrote:
>
>
>>But when I adjust the code to this:
>>
>>sum=['c']
>>
>>it still does not work, despite the fact that sum is not an undefined
>>object, right?
>>
>
> Probably this is what is slightly more compact approach to your
> problem of making sum of numbers:
>
>
>>>>f = lambda *args: reduce(lambda x, y: x+y, args, 0)
>>>>f(1,2,3)
>>>>
> 6
>
> As for slices vs. indices, it is clear that
>
> a[0] is not a[:0]
>
> because a[0] is an element and a[:0] is a subsequence.
>
> I am not sure why do you need to change fun2, but
> this is what will work:
>
> def fun2 (*args):
> sum = args and args[0] or 0
> for next in args[1:]:
> sum = sum + next
> return sum
>
> In any case, it is impossible to make universal summing function without
> specifying the zero-len case.
>
>
> Sincerely yours, Roman Suzi
>
I'm not trying to add string to a list of integeres. What I wanted to do
is to add each argument of func2('a','b','c') to sum=['e']. Since sum is
a list of chars, and the arguments are accessable as a sequence, one
would expect that the addition operation would be correct. On the
interactive shell, it is a trivial operation. But, only when i use it in
the function defenition i get problems. Adding 'a' to ['b'] does not
work, but adding list('a') to ['b'] it does, so, i thought that this
might help my code, but converting the args to a list did not helpe
either . I really didn't get yet!
More information about the Python-list
mailing list