Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

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
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #Python #find #permutations #operators #digit #string #digits #result #answer
ADD COMMENT
Topic
Name
4+7 =