Shivlal Sharma wrote: > 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
Rewrite the ADDS() function like so >>> def ADDS(a, b): ... result = a + 1 ... print(f"ADDS({a}, {b}) --> {result}") ... return result ... to see what's going on: >>> reduce(ADDS, [1,2,3,4,5,6,7,8,9]) ADDS(1, 2) --> 2 ADDS(2, 3) --> 3 ADDS(3, 4) --> 4 ADDS(4, 5) --> 5 ADDS(5, 6) --> 6 ADDS(6, 7) --> 7 ADDS(7, 8) --> 8 ADDS(8, 9) --> 9 9 ADDS is called with the first two values, then with the first result (first value + 1) and the third value then the second result ((first value + 1) + 1) and the fourth value... This can be written recursively as ADDS(ADDS(ADDS(ADDS(ADDS(ADDS(ADDS(ADDS(1, 2), 3), 4), 5), 6), 7), 8), 9) As the second argument is always discarded we get the first a=1 eight times incremented by one, i.e 9. To drive the point home that we always get first item + (len(items) -1): >>> reduce(ADDS, [42,"a","b","c","d"]) ADDS(42, a) --> 43 ADDS(43, b) --> 44 ADDS(44, c) --> 45 ADDS(45, d) --> 46 46 -- https://mail.python.org/mailman/listinfo/python-list