Rotareti Rotareti - 3 months ago 9
Python Question

Python if else statement not working in reduce lambda function

I'm new to

lambda
and
reduce
in Python and I don't understand why this function doesn't work:

def my_func(str):
symbols = ['_', '-']
return reduce(lambda x, y: ' ' + y if x in symbols else x + y, str)

my_func('foo_bar-baz') # 'foo_bar-baz'


I expected the output to be
'foo bar baz'
.

Does anyone understand what's wrong here?

Answer

You seem to be confused about the order of the arguments to reduce's function argument. The first argument is the running total, the second is the new data. In your example, x is the built-up string, y is the new character.

Try this:

def my_func(str):
    symbols = ['_', '-']
    return reduce(lambda x, y: x + (' ' if y in symbols else y), str)

print my_func('foo_bar-baz')  # 'foo bar baz'

Note the bug in this: in the first call to the lambda expression, x is str[0], and y is str[1]. Thus, if the first character in the passed-in string is a symbol, it is not translated.

print my_func('-foo_bar-baz')
-foo bar baz

This can be solved by providing the third argument to reduce():

def my_func(str):
    symbols = ['_', '-']
    return reduce(lambda x, y: x + (' ' if y in symbols else y), str, '')

print my_func('foo_bar-baz')  # 'foo bar baz'
print my_func('-foo_bar-baz')  # ' foo bar baz'