I'm trying to write a function which get:
- An integer. (s)
- A list with integers separated by math symbols.(L)
By using recursion to determinate if the value of s can be calculate from the list by placing braces.
Any ideas for a solution? I thought about using eval() function.
for example:
L = [6,'-',4,'*',2,'+',3]
s=10
Return: True, since: (6-4)*(2+3)=10
L = [6,'-',4,'*',2,'+',3]
s=1
Return: True, since: (6-(4*2))+3=1
L = [6,'-',4,'*',2,'+',3] s=100 Return: False, since there is no valid way to place braces in L which will lead to a solution of 100.
Thanks :)
Let's describe the recursion in words, I think it is better to understand, we just need to define exactly what it does, it is really like induction.
rec function: get an input a list of numbers and return all the combinations of braces(examples later).
base: list with one element, for example [3], the function return (3) which is the only combination. or list with 3 element which simply returns (2+3)
assumption: we can solve it for a list of size N -2, for your example:[6,'-',4,'',2,'+',3] N = 7, so we can solve it for list with size 5 [4,'',2,'+',3] and we will get all the combinations:
Step: solve it for N! what we need to do is to go over all the combination we got from the rec call(if we are on N = 7, its simply 1 and 2 from the example) and we only need to do the following things for each combination: put the current number next to the most left number and operate on it, or put it before the braces and put braces on all the expressions, for our example:
from option 1 we get 2 new options
6 -( (4*2) +(3) )
(6 - 4*2) +(3)
from option 2 we get 2 new options
(6-4) * (2+3)
6 - ( (4) * (2+3))
now the rec function returned all the combinations, we can call eval on each of them to check the result