Let us consider a list with numbers like the following :
a_lst = [1,2,3,2,3,4,5,6,2,2]
Now I need to write a program in python which counts the number of occurrences of let's say "2" using only "reduce" .
I went through the following question as well :
using Python reduce Count the number of occurrence of character in string
It has got a great answer , however I wanted to see if there is any way where I could replace the "if" condition inside the lambda function with like (x == 2) . I mean getting the same thing done by not using the "if"condition explicitly .
I thought of reaching up to a solution by passing a lambda function,which takes another lambda function as an argument to the reduce function . But it turned out to be just a day-dream and nothing else as after passing a lambda function as an argument , calling it inside the outer lambda function body will defeat the purpose of making it a lambda function .
One more fiasco was about wishing for a construct where a lambda function could call itself at the end of its body . (I understand the above line sounds completely meaningless , but what I meant a construct which had the equivalent power of a lambda calling itself )
I have been through the concept of continuation passing style ,where in pythonic terms , a function returns a lambda function which takes the arguments that the function had received .But I am not sure if by definition of continuation is technically accurate . Can it be brought to use to solve this problem ?
fix = lambda f: lambda n: f(n, f), thenfact = fix(lambda n, f: 1 if n == 0 else n*f(n-1, f))defines a factorial function without explicit recursion. - chepnerfact(n) = n!, then, is the fixed-point of a two-argument functionfoo(n, f) = 1 if n == 0 else n * f(n-1, f). - chepnerfixtakes a two-argument function and returns a single-argument function. The return value offixin this example is the single-argument functionfact. (It's probably a little clearer written out withdefstatements, butlambdaexpressions fit in comments better.) - chepner