tokens = { '+': (lambda a, b: a+b, 2), '-': (lambda a, b: a-b, 2), '*': (lambda a, b: a*b, 1), '/': (lambda a, b: a/b if a % b == 0 else False, 1), } def rpn(exp, stack=()): if len(exp) == 0: if len(stack) == 1: return stack[0] raise Exception('Invalid expression') cur = exp[0] if isinstance(cur, int): return rpn(exp[1:], stack + (cur,)) if cur in tokens and len(stack) >= 2: a, b = stack[-2:] func, _ = tokens[cur] result = func(a, b) if result is False: raise Exception('Invalid expression') return rpn(exp[1:], stack[:-2] + (result,)) raise Exception('Invalid expression') def rpn_to_infix(exp, stack=()): if len(exp) == 0: return stack[0][0] cur = exp[0] if isinstance(cur, int): return rpn_to_infix(exp[1:], stack + (cur,)) if cur in tokens: a, b = stack[-2:] _, p = tokens[cur] if isinstance(a, tuple): a, pa = a result = ('(%s)' if pa > p else '%s') % (a,) else: result = '%s' % (a,) result += ' %s ' % (cur) if isinstance(b, tuple): b, pb = b result += ('(%s)' if pb > p else '%s') % (b,) else: result += '%s' % (b,) return rpn_to_infix(exp[1:], stack[:-2] + ((result, p),)) def perms(l, head=()): if len(l) == 0: yield () can_have_token = (len([x for x in head if isinstance(x, int)]) - len([x for x in head if not isinstance(x, int)])) >= 2 for i, x in enumerate(l): if x in tokens and not can_have_token: continue for perm in perms(l[:i] + l[i+1:], head + (x,)): yield (x,) + perm def combs(l, n): if n == 0: yield () return for i, x in enumerate(l): for comb in combs(l[i:], n-1): yield (x,) + comb def variations(l, n): if len(l) < n or l == () or n == 0: yield () return if len(l) == n: yield l return for variation in variations(l[1:], n-1): yield l[:1] + variation for variation in variations(l[1:], n): yield variation def solutions(ints, s=24, n=None): if n == None: n = len(ints) for variation in variations(ints, n): for token_comb in combs(list(tokens.keys()), len(variation)-1): for perm in perms(variation + token_comb): try: ret = rpn(perm) except: continue if ret == s: yield rpn_to_infix(perm) for solution in solutions((5,6,3,4),48,3): print solution
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question