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
I think this is simple enough:
from operator import mul
from functools import reduce
prod = lambda L: reduce(mul, L, 1)
evaluateList = lambda(x, eq): sum(
1 if expr == 'X'
else prod(-1 if i == '-'
else x[int(i)]
for i in expr)
for expr in eq)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With