HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Cleaning up/optimizing numerical guessing game

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
numericalgameoptimizingguessingcleaning

Problem

I'm a Python newbie and I'd like to know how I could clean this up/optimize it (but nothing too advanced, please).

As far as I know, it's working as it should, but if you see any errors then please point it out! This is a numerical guessing game with two symbols in front. You can pretty much see how it works by looking at the print messages.

```
from random import randint, choice
import string
maxguesses = 11 # Default number of max guesses
wins = 0
losses = 0
points = 0 # Points accumulated
games = 0 # Games played
numguesses = 0 # Number of guesses
flag = True
allowed = list(string.digits + '+' + '*')
guesses = '' # Track wrong guesses, resets every game when formula is regenerated
letters = set()
partial = '' # Current progress of guesses

def genform(): # Generate secret formula
global secret, maxguesses
sym = choice(['++','**','+','+']) # Pick operation symbols
num = ''
max = randint(3,9) # Set max between 3 & 9
for i in range(max): # Range of max variable
num = num + str(randint(0,9))
secret = sym + num # Assign secret formula
maxguesses = len(secret)+2 # Max guesses based on length of formula
return secret

def evaluate(formula):
evaluated = ''
s1,s2 = secret[:2]
for i in range(2,len(secret)-1): # Loop after two symbols
evaluated = evaluated + secret[i]
evaluated = (evaluated + s1) if not (i%2) else (evaluated + s2) # Place symbols appropriately
evaluated = evaluated + secret[-1] # Put together
return evaluated

Solution

-
Not good:

points = points - 2 # lots of this kind of code


Good:

points -= 2


-
Not good:

allowed = list(string.digits + '+' + '*')


Good:

allowed = string.digits + '+*' #You don't need list in this case


-
Not good:

max = randint(3,9)


Good:

_max = randint(3,9) # max is a function in standard namespace


-
Not good:

print 'Remaining Guesses: ' + str(maxguesses-numguesses)


Good:

print 'Remaining Guesses: {}'.format(maxguesses-numguesses)


-
Not good:

if bonus == str(eval(evaluate(secret))):   # what do you mean here?


-
Not good:

def evaluate(formula):  
...


Your local var formula was not used in this function. Instead of this, you're using global secret.

-
Not good:

genform()  
...  
return secret


You're returning secret in this function, but you don't use it in your app. secret is global anyway.

That's a briefly view. Please read Google’s Python style guide.

Code Snippets

points = points - 2 # lots of this kind of code
points -= 2
allowed = list(string.digits + '+' + '*')
allowed = string.digits + '+*' #You don't need list in this case
max = randint(3,9)

Context

StackExchange Code Review Q#18476, answer score: 5

Revisions (0)

No revisions yet.