def count_cond(condition):
return lambda x:(((lambda f:(lambda a:f(a(a)))(lambda a:f(lambda *w:a(a)(*w))))(lambda cc: lambda j,m: ((cc(j+1,m+1) if condition(x,m)==True else cc(j,m+1))) if m<=x else j))(0,1))
# Returns a function with one parameter N that counts all the numbers from 1 to N that satisfy the two-argument predicate function Condition, where the first argument for Condition is N and the second argument is the number from 1 to N.
I implemented the function above to do as the note said. It may be kind of abstract, so the following example may be helpful for you to understand what I'm actually doing by it.
>>> count_factors = count_cond(lambda n, i: n % i == 0)
>>> count_factors(12) # 1, 2, 3, 4, 6, 12
6
>>> count_factors(10000)
25
In small scale test cases, it works well. You may found 'max recursion depth exceed', then you could try following lines for a quick fix, as the depth is expected to be about 2n.
import sys
sys.setrecursionlimit(10000000)
But as it comes to lager scale, like 1e6 or somethings like that (I meancount_factors(100000)), python will just return Segmentation Faultand crash, directly go back to the terminal, as the following picture showed.
Segmentation Fault Image
However, if I expand that lambda function into normal function as following, maybe of a little bit low-efficiency, it still works well, even in 1e7 test (it's count_factors(1000000)).
def cc(condition,x,j=0,m=1):
return ((cc(condition,x,j+1,m+1) if condition(x,m)==True else cc(condition,x,j,m+1))) if m<=x else j
I tried to usepython faulthandlerand python ingdb, but they both give nothing valuable. They just showed the program repeating that line again and again until the fault.
I wander if this is a bug or feature of python, or I've done something wrong, and how can I fix this bug.
I would appreciate your generous help.
This question is different from this one, as I use python 3.11, and if I expand this lambda function into normal function, it works well, not the same as what the question above described.