Didn't understand the output of the following Python 3 code with reduce function?

Shivlal Sharma sshivlal9601 at gmail.com
Sat Aug 29 03:55:56 EDT 2020


On Saturday, 29 August 2020 at 02:47:56 UTC+5:30, Ben Bacarisse wrote:
Thanks you all, I was really confused in this code.
> Shivlal Sharma <sshivl... at gmail.com> writes: 
> 
> > I have seen this code on one of competative programming site but I 
> > didn't get it, Why output is 9? 
> > 
> > from functools import * 
> > 
> > def ADDS(a,b): 
> > return a+1 
> > nums = [1, 2, 3, 4, 5, 6, 7, 8, 9] 
> > add = reduce(ADDS, nums) 
> > print(add) 
> > 
> > output: 9
> Hint: 
> 
> reduce(f, [e1, e2]) is f(e1, e2) 
> reduce(f, [e1, e2, e3]) is f(f(e1, e2), e3) 
> reduce(f, [e1, e2, e3, e4]) is f(f(f(e1, e2), e3), e4) 
> 
> Replace f with a function that adds one to its first argument. Does 
> that help? 
> 
> -- 
> Ben.


More information about the Python-list mailing list