Skip to content

Instantly share code, notes, and snippets.

@mpawliuk
Created June 14, 2018 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpawliuk/4711d47967b593804f7acece8b9f65e5 to your computer and use it in GitHub Desktop.
Save mpawliuk/4711d47967b593804f7acece8b9f65e5 to your computer and use it in GitHub Desktop.
This generates a game where there is an algebraic expression whose operations are hidden.
import random
def generate_game(largest_number, length, difficulty):
"""Produce an example of the number game.
- largest_number is the largest possible number that can appear
- length is how many numbers will appear in the problem
- difficulty = 0,1,2. 0 has just addition/subtraction, 1 introduces multiplication, 2 has +,-,*,/
"""
# Set difficulty
operations = ["add", "subtract"]
if difficulty > 0:
operations.append('multiply')
if difficulty > 1:
operations.append('divide')
# Add numbers and operations
game = [random.randint(0,largest_number)]
for i in range(length-1):
game.append(random.choice(operations))
game.append(random.randint(0,largest_number))
# Find solution
copy_game = copy(game)
while 'multiply' in copy_game:
i = copy_game.index('multiply')
copy_game = copy_game[:i-1] + [(copy_game[i-1]*copy_game[i+1])] + copy_game[i+2:]
while 'divide' in copy_game:
i = copy_game.index('divide')
copy_game = copy_game[:i-1] + [(copy_game[i-1]/copy_game[i+1])] + copy_game[i+2:]
while 'subtract' in copy_game:
i = copy_game.index('subtract')
copy_game = copy_game[:i-1] + [(copy_game[i-1]-copy_game[i+1])] + copy_game[i+2:]
solution = sum(copy_game[::2])
# Make hidden game
hidden_game = ""
for i in range(len(game)):
if i % 2 == 0:
hidden_game += str(game[i])
else:
hidden_game += " _ "
hidden_game += " = " + str(solution)
print hidden_game
x = raw_input("Click to see a solution.")
print game
return None
s = int(raw_input("What's the largest number you want to appear? (Enter a whole number larger than 0)"))
l = int(raw_input("How many numbers do you want to appear? (Enter 1,2, ..., 10)"))
d = int(raw_input("What difficulty do you want? 0 = + and - only, 1 contains multiplication, 2 contains all operations."))
for i in range(int(raw_input("How many games do you want to play? (Enter 1,2, ..., 10)"))):
generate_game(s, l, d)
print "Thank you for playing!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment