Created
November 9, 2012 10:53
-
-
Save iEverX/4045128 to your computer and use it in GitHub Desktop.
A solution for the problem http://weibo.com/1915548291/z4eTPtAnv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
plus = lambda x : x + 7 | |
minus = lambda x : x - 5 | |
mul = lambda x : x * 3 | |
div = lambda x : x // 2 | |
func = {'+': plus, | |
'-': minus, | |
'*': mul, | |
'/': div, | |
'#': None, | |
} | |
position = {'begin': 0, 'mid': 1, 'end': 2} | |
class State: | |
def __init__(self, last, pos, value, operation=None): | |
self.last = last | |
self.pos = pos | |
self.value = value | |
self.operation = operation[:] if operation else [] | |
self.key = '{0}{1}{2}'.format(self.pos, self.last, self.value) | |
def todo(state, opt): | |
value = func[opt](state.value) | |
if state.pos == position['begin'] or state.pos == position['end']: | |
pos = position['mid'] | |
elif opt == '+' or opt == '/': | |
pos = position['begin'] | |
else: | |
pos = position['end'] | |
return State(opt, pos, value, state.operation[:] + [opt]) | |
def todos(state, *opts): | |
states = [] | |
for opt in opts: | |
states.append(todo(state, opt)) | |
return states | |
def next_state(current): | |
ns = [] | |
if current.pos == position['begin']: | |
if current.last == '#': | |
ns.extend(todos(current, '+', '/')) | |
elif current.last == '/': | |
ns.extend(todos(current, '+')) | |
else: | |
ns.extend(todos(current, '/')) | |
elif current.pos == position['end']: | |
if current.last == '*': | |
ns.extend(todos(current, '-')) | |
else: | |
ns.extend(todos(current, '*')) | |
else: | |
last = current.last | |
if last == '+': | |
ns.extend(todos(current, '-', '*', '/')) | |
elif last == '/': | |
ns.extend(todos(current, '+', '-', '*')) | |
elif last == '*': | |
ns.extend(todos(current, '+', '-', '/')) | |
else: | |
ns.extend(todos(current, '+', '*', '/')) | |
for state in ns: | |
if state.key in state_keys: | |
ns.remove(state) | |
else: | |
state_keys.add(state.key) | |
return ns | |
def answer(operation): | |
nums = {'+': 7, '-': 5, '*': 3, '/': 2} | |
num = begin | |
for x in operation: | |
next_num = func[x](num) | |
print('{0}: {1} {0} {2} = {3}'.format(x, num, nums[x], next_num)) | |
num = next_num | |
begin = 2011 | |
end = 2012 | |
states = [State('#', position['begin'], begin)] | |
state_keys = {states[0].key} | |
if __name__ == '__main__': | |
while True: | |
current = states.pop(0) | |
ns = next_state(current) | |
for state in ns: | |
if state.value == end and state.pos == position['end']: | |
answer(state.operation) | |
print(len(state.operation)) | |
raise SystemExit | |
else: | |
states.extend(ns) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment