I have a list of m elements and n different numbers that appear in a list of strings. The list follows the following format example
eq = ['12', '2', '3', '-123', '-1', 'X']
Note, X represents the constant 1, other than the variable 1. I want to be able to convert this to a lambda function that takes in a list x and acts like this list was summed together. For our example the function would be
f(x) = x[1]*x[2] + x[2] + x[3] - x[1]*x[2]*x[3] - x[1] + 1
I know how to do this with a normal function, but I wanted to get it to work with a lambda and hit a wall. Any help would be appreciated!
Here is the function that works for the problem:
def evaluateList(x, lst):
num = 0
for term in lst:
if term[0] == "X":
num += 1
elif term[0] == "-":
num -= reduce(lambda x,y: x*y, [x[int(y)-1] for y in term[1:]])
else:
num += reduce(lambda x,y: x*y, [x[int(y)-1] for y in term])
return num
numis changing value over iterations, that implementation won't work in a lambda. But all is not lost! Any stateful iterative algorithm can be translated to a stateless one using combinators likemap,reduce, andfilter. This algorithm will look quite different than your function above, but it is doable. Let me play with it and see what I can come up with.