[Tutor] [Tutor} Why doesn't it choose a new number each time?

Geoframer geoframer at gmail.com
Thu Feb 15 11:43:55 CET 2007

```The one thing people told me when i started learning python was that python
has this lovely structure called dictionaries. Your particular problem is
very easy to solve using dictionaries in about 12 lines (i coded it myself
just to see ;-)).

For instance you could define the various values as a dictionary :
values = {1:'rock', 2:'paper', 3:'scissors'}

and the outcome of possible combinations (cchoice, hchoice) as :
combinations = {(1,1):'Tie game!', (1,2):'You win!', (1,3):'You lost!',
(2,1):'You lost!', (2,2):'Tie game!', (2,3):'You win!',
(3,1):'You win!', (3,2):'You lost!', (3,3):'Tie
game!'}

That way it's very easy to take a random value for computer , get input for
human player and print the result in a single print like so :
print "AI chose %s, you chose %s. %s", %(values.get(cchoice),values.get
(hchoice),combinations.get((cchoice,hchoice)))

Probably this is not unlike Alan suggest, but i got confused when i read

HTH - Geoframer

On 2/15/07, Rikard Bosnjakovic <rikard.bosnjakovic at gmail.com> wrote:
>
> On 2/15/07, Nathan Pinno <falcon3166 at hotmail.com> wrote:
>
> > and that was a suggestion. (Thanks!) But can anyone explain why I can
> > shorten the code? I looked at it a long while yesterday, and came up
> with
> > nothing. The only thing I decided was to try to get it to the GUI stage.
>
> If you take a look at your if-cases, you see that a lot of strings in
> there are the same. The code is therefore redundant, and this is what
> can be trimmed down.
>
> Consider this code:
>
> if var1 = 1 and var2 = 0:
>   print "Var1 is 1, var2 is 0"
> if var1 = 0 and var2 = 0:
>   print "Var1 is 0, var2 is 0"
> if var1 = 1 and var2 = 1:
>   print "Var1 is 1, var2 is 1"
> if var1 = 0 and var2 = 1:
>   print "Var1 is 0, var2 is 1"
>
> This scope is redundant in a lot of ways and can be trimmed down to
> one if and one print:
>
> if (var1 in [0,1]) and (var2 in [0,1]):
>   print "Var1 is %d, var2 is %d" % (var1, var2)
>
> Your code is similiar to the above. It takes time to learn how to trim
> down redundant code. Vast knowledge of a language itself is not
> required, but a pretty solid knowledge about the basics is probably
> required. If you are entirely new to programming, it might be
> cumbersome though.
>
> Give it a try, and don't hesitate to ask again.
>
> --
> - Rikard.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070215/ea249ca9/attachment.html
```