guess_result compares a player's guess with a secret code and reports two counts: digits in the correct positions and digits present elsewhere in the code. It supports the feedback step of a Bulls and Cows game. section 10.3.2 section 10.3.4
The function follows a small input-process-output design:
- Input: two same-length strings, guess and secret_code. section 10.3.3
- Process: inspect each index, count exact matches, then count nonmatching guess digits found elsewhere in the secret code. section 10.3.4
- Output: a two-integer list, [correct, misplaced]. section 10.3.3
- Use elif rather than a separate if so an exact match is not also counted as misplaced. section 10.3.4
Worked results
guess_result('3821', '1862') returns [1, 2]: the 8 is correctly placed, while the 2 and 1 occur in different positions. guess_result('1234', '4321') returns [0, 4], because every digit exists but none is correctly positioned. section 10.3.4
Listing 10.4 Function guess_result to get the result of a guess
def guess_result(guess, secret_code):
'''
guess and secret_code are strings of the same length.
Return a list of two values:
the first value is the number of indices in guess where
the character at that index matches the character at the
same index in secret_code; the second value is the
number of indices in guess where the character at that
index exists at a different index in secret_code.
>>> guess_result('3821', '1862')
[1, 2]
>>> guess_result('1234', '4321')
[0, 4]
'''
correct = 0 #1
misplaced = 0 #2
for i in range(len(guess)): #3
if guess[i] == secret_code[i]: #4
correct += 1 #5
elif guess[i] in secret_code: #6
misplaced += 1 #7
return [correct, misplaced] #8
The complete listing shows the counters, index-based loop, conditional comparison, and returned list. section 10.3.4
