I\'m a beginner to Python programming and have come upon an issue with my current assignment. The assignment reads as follows...
You can solve your problem very elegantly with the Python function map(). (Not quite as elegantly as I originally thought, but still pretty nicely.)
guess = "1879" # or [ '1', '8', '7', '9' ]
answer = "1234"
map() works like this: you give it a function as its first argument, and one or more sequences as arguments following that. It then takes takes that function and applies it first to both the first elements, then to both the second elements, and so on. For instance:
>>> def f(a,b):
>>> return a + b
>>> map( f, [1,2,3,4], [ 10, 20, 30, 40 ] )
[ 11, 22, 33, 44 ]
Now, you have two sequence of characters, "guess" and "answer". You could write a function that returns X if they're equal and - otherwise like this:
>>> def mastermind_hint( a, b ):
>>> return "X" if a == b else "-"
That's not quite enough, you also need to put in the 'O's. For this you need to use the entire "answer" sequence at once:
>>> def mastermind_hint( a, b ):
>>> if a == b: return "X"
>>> if a in answer: return "O"
>>> return "-"
Using map, we can apply that to the sequences you have:
>>> map( mastermind_hint, guess, answer )
[ "X", "-", "-", "-" ]
Now, right now we're giving away more information than we're supposed to because the positions of our hints correspond to the positions of the guess characters. A simple way to hide this information is to sort the sequence. Python has a sorted() function which does this:
>>> sorted( map( mastermind_hint, guess, answer ) )
[ "-", "-", "-", "X" ]
All that remains is to join this into a single string:
>>> "".join( sorted( map( mastermind_hint, guess, answer ) ) )
"---X"