Skip to content Skip to sidebar Skip to footer

Understanding Complex Code With Reduce(), Python

Can someone explain the structure of reduce() in the following example: def f2(list): return reduce(lambda string, item: string + chr(item), list, '') I know that f2 conve

Solution 1:

return reduce(lambda string, item: string + chr(item), list, "")

roughly translates to

string = ""for item in list:
    string = string + chr(item)
returnstring

Solution 2:

Reduce does something usually called a fold. E.g., if you have a list ls = [a,b,c,d] and a binary operation def plus(x,y): x + y, then reduce(plus, ls) gets folded to

plus(plus(plus(a, b), c), d)

which equals

(((a+b)+c)+d)

Your f2 is doing something similar, namely appending strings (after converting them from integers): (I really hope those parens match...)

(((("" + chr(a)) + chr(b)) + chr(c)) + chr(d))

with a supplied initial value of "" (which is needed when a folding operation has two different input types)

@ python experts: I'm not sure if reduce is a left fold, it seemed more naturally to me. Please tell me if I'm wrong.

Solution 3:

The code applies chr() to every element of the list, and concatenates the results into a single string.

The reduce() call is equivalent to the following:

return "" + chr(list[0]) + chr(list[1]) + ... + chr(list[list.length - 1])

The "" is the third argument to reduce(). The lambda function in

return reduce(lambda string, item: string + chr(item), list, "")

is called for every item in the list. It simply appends chr(item) to the result of the previous iteration.

For more examples of using reduce(), see Useful code which uses reduce() in python

Post a Comment for "Understanding Complex Code With Reduce(), Python"