Reputation: 61
I have
>>> reduce( (lambda x,y: x + y), [1,2,3])
6
And
>>> reduce( (lambda x,y: x + y), ['cat','dog','hat'])
'catdoghat'
Then, I'd like to get the sum of all string elements in the list:
>>> reduce( (lambda x,y: len(x) + len(y)), ['cat','dog','hat'])
It produces an error.
What am I doing wrong?
Upvotes: 2
Views: 1380
Reputation: 95948
Think about your reduce operation:
(len((len('cat') + len('dog')))+ len('hat'))
You will end up calling len
on an int
. You probably want:
sum(map(len, ['cat','dog','hat']))
And stop re-inventing the wheel and using reduce
for sum
.
Note also, using sum
(which is equivalent to reduce(lambda x,y: x+y, ...)
is going to have terrible performance for strings, i.e. O(n^2). Instead, use ''.join(sequence_of_strings)
Indeed, the interpreter will yell at you if you even try!
>>> sum(['a','b','c'], '')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]
Upvotes: 4
Reputation: 53525
reduce is a process in which you iteratively go over all the items and apply an operation, let's try to do it with your example:
reduce( (lambda x,y: len(x) + len(y)), ['cat','dog','hat'])
so first x
is 'cat' and y
is 'dog' and the output is 6, now we'll have x
as 6 and y
as 'hat' and we'll fail on len(6)
What you want to do instead is sum the lengths of the strings, you can use map
for that because unlike reduce
map applies a function on all the items (which is exactly what you want - to apply len
to each and every item) and sum will take care of the addition:
sum(map(len, ['cat','dog','hat']))
Upvotes: 3