[Tutor] How do I go about this? [was Re: Who uses input()? [wasRe: question on "input"]]
Alan G
alan.gauld at freenet.co.uk
Thu Jul 28 02:02:47 CEST 2005
>I first posted my question in this post, but no one seemed to answer
>me.
Didn't notice because of the subject. A good reason to use meaningful
subject lines!
>> for example. If there is, show me it, please. I'm getting confused
>> writing
>> my MasterMind and don't want to screw up bad, e.g. repeat the same
>> answer in a different way.
This is quite tricky, as I discovered when I wrote the mastermind game
code
that is on the CD ROM with my book.
Here is the approach that I used:
# aGuess.value() is the set of 4 numbers.
# bulls are black markers, cows are white.
# self.goal is the seqience that we are comparing the guess to.
def eval(self, aGuess):
bulls, cows = 0,0
# create a dictionary of 'what' v 'how many'
check = {}
for i in aGuess.value():
if check.has_key(i):
check[i] = check[i] + 1
else: check[i] = 1
# same for the goal
goalchk = {}
for i in self.goal:
if goalchk.has_key(i):
goalchk[i] = goalchk[i] + 1
else: goalchk[i] = 1
# Now total cows = match of guess and goal
for i in check.keys():
if i in self.goal:
if goalchk[i] > check[i]:
cows = cows + check[i]
else: cows = cows + goalchk[i]
# is it a bull?
for i in range(4):
item = aGuess.value()[i]
if item == self.goal[i]:
bulls = bulls + 1
# now reduce cows by number of bulls
cows = cows - bulls
return (bulls,cows)
The full program uses my Games framewoirk as described in the book,
but the Target.eval() method is the one that compares the target
with the guess.
The code above can be optimised quie a bit but I tried to keep it
simple enough (and Python v1.5.2 compliant so no True/False values!)
for one of my readers to grok it without explanation - its only on
the CD ROM not in the text...
And if anyone comes up with a simpler algorithm (and I'm sure there
is one!) I'll be pleased to see it too.
HTH,
Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list