Skip to content

Instantly share code, notes, and snippets.

@tomleibo
Last active January 5, 2019 15:06
Show Gist options
  • Save tomleibo/b24937d508131a97039c460ec2e6e68e to your computer and use it in GitHub Desktop.
Save tomleibo/b24937d508131a97039c460ec2e6e68e to your computer and use it in GitHub Desktop.
Solves levels in the calculator game
import re
print("Enter intial value:")
initial = int(input())
print("Enter goal:")
target = input()
print("Enter number of moves:")
moves = input()
print("Enter available buttons separated by commas (1, +1, -1, x2, /2, +/-, sum, 12=>34, reverse, <<, ^3, >, <, mirror)")
ops = map(str.strip,raw_input().split(','))
D = False
def sum_of_digits(x):
sum = 0
while x > 0:
sum += x%10
x /= 10
return sum
def reverse(x):
sum = 0
while x > 0:
sum *= 10
sum += x%10
x /= 10
return sum
def shift_right(x):
length = len(str(x))
first_digit = x % 10
x //= 10
x += (10 ** (length-1) * first_digit)
return x
def shift_left(x):
length = len(str(x))
exp = 10 ** (length-1)
last_digit = x // exp
x %= exp
x *= 10
x += last_digit
return x
def mirror(x):
result = x
while x > 0:
result *= 10
result += x % 10
x //= 10
return result
# For each operator string return an operation as lambda(a,b) and b where a is the original number.
def parse_op(arg):
operations = [ (r"^([0-9]+)$", lambda x,y: x * (10 ** len(str(y))) + y),
(r"^\+([0-9]+)$", lambda x,y: x + y),
(r"^-([0-9]+)$", lambda x,y: x - y),
(r"^x([0-9]+)$", lambda x,y: x * y),
(r"^/([0-9]+)$", lambda x,y: x / y),
(r"^\+\/\-$", lambda x,y: -x),
(r"^sum$", lambda x,y: sum_of_digits(x) ),
(r"^([0-9]+)=>([0-9]+)$", lambda x,y: str(x).replace(str(y[0]),str(y[1]))),
(r"^reverse$", lambda x,y: reverse(x) ),
(r"^<<$", lambda x,y: x // 10 ),
(r"^\^([0-9]+)$", lambda x,y: x ** y ),
(r"^>$", lambda x,y: shift_right(x) ),
(r"^<$", lambda x,y: shift_left(x) ),
(r"^mirror$", lambda x,y: mirror(x) )]
for op in operations:
match = re.search(op[0],arg)
if match:
button = match.group(0)
operation = op[1]
if match.lastindex is 0 or match.lastindex is None:
operand = 0
elif match.lastindex is 1:
operand = int(match.group(1))
else:
operand = (int(match.group(1)),int(match.group(2)))
return operation,operand,button
raise Exception("Could not parse operator")
def solve(initial, ops, target, moves_left, path):
if initial == target:
return path
elif moves_left <= 0:
return False
else:
for op in ops:
operation = op[0]
operand = op[1]
button = op[2]
result = int(operation(initial,operand))
if D:
print("result = "+str(result))
full_path = solve(result,ops,target,moves_left-1,path + " " +button)
if full_path:
return full_path
return False
if D:
op = parse_op(ops[0])
x = op[0](initial,op[1])
print(x)
else :
operations = map(parse_op,ops)
print(solve(initial,operations, target, moves, ""))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment