Skip to content

Instantly share code, notes, and snippets.

@t8ch
Created November 5, 2019 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save t8ch/fe0db9101288d2ff2b0b79b76265b59f to your computer and use it in GitHub Desktop.
Save t8ch/fe0db9101288d2ff2b0b79b76265b59f to your computer and use it in GitHub Desktop.
function that finds operations in between numbers such that equation is satisfied
from numpy import *
import itertools
__all__ = ['find_placeholders']
__author__ = "Tim Herfurth <timherfurth87@gmail.com>"
# # function that finds operations in between numbers such that equation is satisfied
# possible operations
list_of_all = [add, subtract, multiply, divide]
list_of_all = ['+',"-","*","/"]
def find_placeholders(a,c):
'''
Finds a combination of basic mathematical operations (+,-,*,/) between numbers in a that yields c
Parameters
----------
a: List of numbers on left-hand side of equation in between which mathematical operation is to be determined
c: Number that represents right-hand side of equation
Returns
---------
List of mathematical operations that satisfy equation. If no solution can be found an according string is returned.
Example
---------
Task to solve: 5_3_6=10 where _ have to be determined
>>> find_placeholders([5,3,6],10)
['/', '*']
'''
n = len(a)
# create all possible combinations of signs and append 0, which is later removed
operations = [p for p in itertools.product(list_of_all, repeat=n-1)]
operations = [list(x)+['0'] for x in operations]
# combine numbers and operations to one string per combination
str1 = list(map(str, a))
left_hand_expressions = array([''.join(''.join(x) for x in zip(str1,x))[:-1] for x in operations])
# evaluate equations (and taking care of division by zero); stop after first equality is found
equation_holds = -1
for eq_n, eq in enumerate(left_hand_expressions):
try:
if eval(eq)==c:
equation_holds = eq_n
break
except ZeroDivisionError:
pass
# return operations that satisfy equation
if equation_holds == -1:
return 'no solution found'
else:
return operations[eq_n][:-1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment