Skip to content

Instantly share code, notes, and snippets.

@molguin92
Created November 12, 2018 20:17
Show Gist options
  • Save molguin92/138a6cb72bae215f0e0f9fb601a15882 to your computer and use it in GitHub Desktop.
Save molguin92/138a6cb72bae215f0e0f9fb601a15882 to your computer and use it in GitHub Desktop.
Brute Force 8s Puzzle
#!/usr/bin/env python3
import random
choices = list('8+*-/')
result = None
while result != 100:
eights_left = 8
expr = ''
on_operator = True
while eights_left > 0:
if on_operator:
# on operator, next element needs to be an eight
expr = expr + '8'
eights_left -= 1
on_operator = False
else:
# on an eight, next element can be anything
elem = choices[random.randint(0, len(choices) - 1)]
expr = expr + elem
if elem == '8':
eights_left -= 1
else:
on_operator = True
try:
result = eval(expr)
except Exception as e:
print('Invalid expression?')
print(expr)
print(expr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment