Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Python find permutations of operators between each digit in a given string of digits will result in a particular answer

from itertools import permutations
numbers   = ["1","9","8","2"]
target    = 24
operators = ["+","-","*","/"]
for values in permutations(numbers,len(numbers)):
    for oper in permutations(operators,len(numbers)-1):
        formula = "".join(o+v for o,v in zip([""]+list(oper),values))
        if eval(formula) == target: print(formula,"=",target)
Comment

Python find permutations of operators between each digit in a given string of digits will result in a particular answer

from itertools import permutations,combinations_with_replacement
numbers   = ["1","1","1","8"]
target    = 10
operators = ["+","-","*","/"]
seen      = set()
for values in permutations(numbers,len(numbers)):
    for operCombo in combinations_with_replacement(operators,len(numbers)-1):
        for oper in permutations(operCombo,len(numbers)-1):
            formula = "".join(o+v for o,v in zip([""]+list(oper),values))
            if formula not in seen and eval(formula) == target:
                print(formula,"=",target)
                seen.add(formula)
Comment

Python find permutations of operators between each digit in a given string of digits will result in a particular answer

from itertools import permutations,combinations_with_replacement
numbers   = ["9","8","1","2"]
target    = 24
operators = ["+","-","*","/"]
groups    = ['X+X+X+X', 'X+X+(X+X)', 'X+(X+X)+X', '(X+X+X)+X', '(X+X)+X+X', 'X+(X+X+X)', '((X+X)+X)+X', 'X+(X+(X+X))', 'X+((X+X)+X)', '(X+X)+(X+X)', '(X+(X+X))+X']
seen      = set()
for values in permutations(numbers,len(numbers)):
    for operCombo in combinations_with_replacement(operators,len(numbers)-1):
        for oper in permutations(operCombo,len(numbers)-1):
            formulaKey = "".join(oper+values)
            if formulaKey in seen: continue # ignore variations on parentheses alone
            for pattern in groups:
                formula = "".join(o+p for o,p in zip([""]+list(oper), pattern.split("+")))
                formula = "".join(v+p for v,p in zip([""]+list(values),formula.split("X")))
                try:
                    if eval(formula) == target:
                        print(formula,"=",target)
                        seen.add(formulaKey)
                        break 
                except: pass
Comment

Python find permutations of operators between each digit in a given string of digits will result in a particular answer

from itertools import product
import re
def groupPatterns(count,pattern=None):
    arr = pattern or "X"*count
    if len(arr) < 2 : return [arr]
    result = []
    for mid in range(1,len(arr)):
        leftPattern  = groupPatterns(count,arr[:mid])
        rightPattern = groupPatterns(count,arr[mid:])
        for left,right in product(leftPattern,rightPattern):
            result += [left + right]
            if len(left)  > 1 : result += ["(" + left + ")" + right]
            if len(right) > 1 : result += [left + "(" + right + ")"]
            if len(left) > 1 and len(right) > 1: 
                result += ["(" + left + ")(" + right + ")"]
    if pattern: return result # recursion
    patterns = [] # final, add "+" between X value placeholders or groups
    for pat in sorted(set(result),key=lambda x:len(x)):
        pat = re.sub("X(?=X)", r"X+",  pat)  # XX --> X+X
        pat = re.sub("X(",    r"X+(", pat)  # X( --> X+(
        pat = re.sub(")X",    r")+X", pat)  # )X --> )+X
        pat = re.sub(")(",   r")+(", pat)  # )( --> )+(
        patterns.append(pat)
    return patterns
Comment

Python find permutations of operators between each digit in a given string of digits will result in a particular answer

from itertools import permutations,combinations_with_replacement
def numbersToTarget(numbers,target,reuseOper=True,allowGroups=True,operators=["+","-","*","/"]):   
    groups      = groupPatterns(len(numbers)) if allowGroups else [ "+".join("X"*len(numbers)) ]
    seen        = set()
    for values in permutations(numbers,len(numbers)):
        for operCombo in combinations_with_replacement(operators,len(numbers)-1) if reuseOper else [operators]:
            for opers in permutations(operCombo,len(numbers)-1):
                formulaKey = str(opers)+str(values)
                if formulaKey in seen: continue # ignore variations on parentheses alone
                for pattern in groups:
                    formula = "".join(o+p      for o,p in zip([""]+list(opers), pattern.split("+")))
                    formula = "".join(str(v)+p for v,p in zip([""]+list(values),formula.split("X")))
                    try:
                        if eval(formula) == target:
                            seen.add(formulaKey)
                            yield formula
                            break 
                    except: pass

for formula in numbersToTarget([9,8,1,2],24):
    print("24 =",formula)
for formula in numbersToTarget([9,8,1,2,5],0,allowGroups=False):
    print("0 =",formula)
Comment

PREVIOUS NEXT
Code Example
Python :: # sort the dictionary 
Python :: loader.py line 19 in get_template 
Python :: clear terminal anaconda 
Python :: double except python 
Python :: extended slices [::2] 
Python :: pandas replace column values 
Python :: splitting Feature and target using iloc 
Python :: Data type based on rows 
Python :: Specifying your data type 
Python :: insertion sort algorithm in descending order 
Python :: pip install time python 
Python :: Command to import the Schema interface from voluptuous 
Python :: add Elements to Python list Using extend() method 
Python :: how to create dict key with list default -2 
Python :: glom safely interact with dictionary 
Python :: codeforces 1133A in python 
Python :: empty python 
Python :: OSError Traceback (most recent call last) <ipython-input-74-8920269c5588 in <module() 9 10 run_with_ngrok(app) --- 11 app.run() 
Python :: move python file 
Python :: Python NumPy atleast_2d Function Example 
Python :: display colors in python console 
Python :: Python NumPy asanyarray Function Example Scalar to an array 
Python :: django on-delete options 
Python :: structure conditionnelle python 
Python :: Python __le__ magic method 
Python :: track keyboard press pynput 
Python :: lambda function in python to shut ec2 at the time zone 
Python :: discord python bot input 
Python :: Creating a Dictionary using built-in function dict() 
Python :: displaying print output in a textbox 
ADD CONTENT
Topic
Content
Source link
Name
9+8 =