[Tutor] [Tutor} Why doesn't it choose a new number each time?
Alan Gauld
alan.gauld at btinternet.com
Thu Feb 15 10:05:27 CET 2007
"Nathan Pinno" <falcon3166 at hotmail.com> wrote
> But can anyone explain why I can shorten the code?
There are a few things you could do but one very powerful
trick is to use a table driven approach. Thus:
rps = {0:'rock',1:'paper',2:'scissors'} # use zero to match list
index
results = [
# zeroth item AI chose rock
['You chose Rock : Tied Game',
'You chose Paper: You win!',
'You chose scissors, AI Wins!'],
# index one is AI chose paper
['You chose Rock, AI Wins!'
...etc....],
# index 3 AI chose scissors
['You chose Rock, You win!', ....etc]
]
Now all your if/else logic becomes:
tool = choice(range3))
user = int(raw_input(....)
print 'AI chose ', rps[tool], results[tool][user]
And you can reduce that further by using multiple tables
of strings and the results table simply becomes a collection
of indexes into those tables. This is starting to get into a
database topic called normal forms which is probably a
tad advanced for this case!
HTH,
Alan G.
More information about the Tutor
mailing list