patternpythonMinor
Mastermind: Evaluating the guess
Viewed 0 times
mastermindtheguessevaluating
Problem
The
-
Without changing the essence of the algorithm: Can I implement the
-
Is there a more straightforward algorithm?
evaluate_guess function below returns the evaluation of a guess with respect to Mastermind game rules:# sample secret code and guess
secret_code = ["a", "a", "c", "a"]
guess = ["c", "a", "a", "b"]
def evaluate_guess(secret_code, guess):
score = []
temp_list = secret_code.copy()
for i in range(len(secret_code)):
if guess[i] == temp_list[i]:
score.append(1)
temp_list[i] = None
elif guess[i] in temp_list:
score.append(0)
temp_list[temp_list.index(guess[i])] = None
score.sort(reverse=True)
return score
print(evaluate_guess(secret_code, guess))
>>> [1, 0, 0]-
Without changing the essence of the algorithm: Can I implement the
evaluate_guess function in a more Pythonic way? Is it possible to implement the algorithm in a purely functional fashion?-
Is there a more straightforward algorithm?
Solution
Most of the solutions provided so far is hard to read, and you need to really think before you understand what is happening, so I would like to propose an alternative approach as a response to a more straightforward algorithm:
The only magic in this code is the joining of
def evaluate_guess(secret_code, guesses):
score = []
remaining_secrets = []
remaining_guesses = []
# Check exact matches
for guess, secret in zip(secret_code, guesses):
if guess == secret:
score.append(1)
else:
remaining_guesses.append(guess)
remaining_secrets.append(secret)
# Check wrong placing
for guess in remaining_guesses:
if guess in remaining_secrets:
score.append(0)
remaining_secrets.remove(guess)
return scoreThe only magic in this code is the joining of
secret_code and guesses using zip which joins them index for index. This allows for, in my opinion, code that is easier to understand instead of list comprehensions, ifilters, index searching, sorting, sliceing and other stuff.Code Snippets
def evaluate_guess(secret_code, guesses):
score = []
remaining_secrets = []
remaining_guesses = []
# Check exact matches
for guess, secret in zip(secret_code, guesses):
if guess == secret:
score.append(1)
else:
remaining_guesses.append(guess)
remaining_secrets.append(secret)
# Check wrong placing
for guess in remaining_guesses:
if guess in remaining_secrets:
score.append(0)
remaining_secrets.remove(guess)
return scoreContext
StackExchange Code Review Q#111637, answer score: 5
Revisions (0)
No revisions yet.