Skip to content

Instantly share code, notes, and snippets.

@dragoncoder047
Last active March 22, 2024 14:38
Show Gist options
  • Select an option

  • Save dragoncoder047/8e43c247709c52762e909d502b8a9d49 to your computer and use it in GitHub Desktop.

Select an option

Save dragoncoder047/8e43c247709c52762e909d502b8a9d49 to your computer and use it in GitHub Desktop.
Program to find all the solutions to the "The Fours Have It" math worksheet
## Well, almost all of them. There are solutions for 13 but this doesn't find those for some odd reason
import sys
def sqrt(x):
try:
return {169: 13, 144: 12, 121: 11, 100: 10, 81: 9,
64: 8, 49: 7, 36: 6, 25: 5, 16: 4, 9: 3, 4: 2}[x]
except KeyError:
raise ValueError("don't want floats") from None
def fact(n):
assert 2 < n < 10
prod = 1
for i in range(1, n+1):
prod *= i
return prod
def mpow(x, y):
if int(x) != x:
raise ValueError
if x > 9999 or y > 99999:
raise OverflowError
return pow(x, y)
operators = [
# format str, is 1-op, noncommutative
("{}+{}", False, False), # a+b
("{}-{}", False, True), # a-b
("{}*{}", False, False), # a*b
("{}/{}", False, True), # a/b
("mpow({}, {})", False, True), # a**b
("sqrt({})", True, None), # sqrt(a)
("fact({})", True, None), # a!
("{}{}", False, True), # two 4s -> 44
]
def expressions(num=4, count=4, cando1op=2):
if count == 0:
raise RuntimeError
out = []
for op in operators:
if op[1]:
if cando1op:
parts = expressions(num, count, cando1op-1)
# it's a one-expression operator, there's nothing else we can do
for p in parts:
out.append(op[0].format(p))
elif count > 1:
parts = expressions(num, count-1)
for p in parts:
out.append(op[0].format(p, num))
if op[2]:
out.append(op[0].format(num, p))
return out or [str(num)]
print("Generating expressions...")
ex = expressions(4, 4)
d = {}
num = len(ex)
i = 0
th = 0
print(num)
# evaluate all the expressions
for e in ex:
try:
v = eval(e)
if v not in d:
d[v] = set()
d[v].add(e)
except KeyboardInterrupt:
raise
except:
pass
i += 1
if i == 1000:
# print progress report
th += 1
print(f"{th}000/{num}")
i = 0
try:
if "idlelib" in sys.modules:
raise ModuleNotFoundError # running under IDLE breaks IPython REPL
import IPython
IPython.embed()
except ModuleNotFoundError:
import code
code.InteractiveConsole(locals=globals()).interact()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment