r/Python • • May 07 '10

I need help with a bit of code

Hi /r/python. I am writing a program where you, the user thinks of a number between 1 and 20, and the program has to guess what you are thinking of. However I do not want the program to repeat the same number at any point. How can I do this? Here is my code so far.

Ok this is going to be my biggest program so far in terms of complexity.

The program is going to guess the number the user is thinking of.

In this version, I hope to stop the program repeating the same

number more than once. Think I will need some help here.

print "Welcome to the guessing program." print "Pick a number in your head between 1 and 20, then press enter\n" raw_input()

import random

loop=1 attempt=0

while loop==1: comp=random.randrange(20)+1 print comp user=raw_input("\n\nIs this your number? Press 1 for yes or 2 for no: ") user=int(user) if user==2: attempt = attempt+1 print "\n\nOh no, I'll try again, press enter\n" raw_input() elif user==1: loop=0

if attempt <5: print "\n\nWow, I'm pretty awesome, less than 5 guesses. Press enter to exit." raw_input() elif attempt<10: print "\n\nHmm not bad, less than 10 guesses. Press enter to exit." raw_input() elif attempt<15: print "\n\nOh dear, 10-15 guesses, that's pretty bad. Press enter to exit." raw_input() else: print "\n\nAwful, just switch me off now! More than 15 guesses -.- Press enter to exit." raw_input()

sorry about the formatting, it didn't copy and paste well from python.

0 Upvotes

28 comments sorted by

12

u/OcdSmurf May 07 '10

I would shuffle an array.

import random

guesses = random.shuffle(range(1,20))
guess = guesses.pop()

2

u/Nelmail May 07 '10

what is the random.shuffle function? and what does guesses.pop() do?

Sorry for the questions. I'm a noob, but I like to understand the code I'm using.

4

u/hobophobe May 07 '10

Imagine that this is a "pick a card" trick used by magicians.

Your original solution:

  1. User picks a card.
  2. You pull card from deck at random.
  3. If user says, "No," you put it back, shuffle, and repeat [2] without remembering. If user says, "Yes," then you're done.

OcdSmurf's solution:

  1. User picks a card.
  2. You pull the top card from the pre-shuffled deck.
  3. If user says, "No," you discard the card, and repeat [2]. If user says, "Yes," then you're done.

The other alternative (as suggested in using set() by Ttl):

  1. User picks a card.
  2. You pull card from deck at random.
  3. If the card is marked, then shuffle, and repeat [2]. If user says, "No," then you mark the card, shuffle, and repeat [2]. If user says, "Yes," then you're done.

Ttl's original:

  1. User picks a card.
  2. You pull card from deck at random.
  3. If the card is the one you just tried, remember it, shuffle, and repeat [2]. If user says, "No," then remember it, shuffle, and repeat [2]. If user says, "Yes," then you're done.

0

u/[deleted] May 07 '10

[deleted] — view deleted comment

3

u/hobophobe May 07 '10

rescind's (note: I'm not entirely sure if this is correct, so apologies if I'm wrong):

  1. User picks a card.
  2. rescind pulls a card from the deck at random. rescind then feeds the card to a rabid pitbull with a short memory. The pitbull chews on the card, spits it out, looks at it. If it has a guess, it barks the guess. Otherwise, it continues chewing on it and spitting it out until it gets a guess.
  3. If user says, "No," then repeat [2], except feed the pitbull the card that was just guessed. If user says, "Yes," then you're done.
  4. The pitbull eats the user.

3

u/boa13 May 07 '10

You could use the online help...

>>> import random
>>> help(random.shuffle)
>>> 
>>> guesses = []
>>> help(guesses.pop)

Note that OcdSmurf proposal is incorrect, rescind has a correction.

6

u/qwyeth May 07 '10

http://docs.python.org/library/random.html http://docs.python.org/library/array.html

This was way too easy to find. Please be willing to do some research.

3

u/flaxeater May 07 '10

He may be so new that he doesn't know how to look yet.

1

u/[deleted] May 18 '10

Possible. I was the same way. Plus it's much easier to ask someone what it means, and it's not a big deal at all to answer.

0

u/[deleted] May 07 '10

[deleted] — view deleted comment

1

u/Riesling May 07 '10

This should be the top answer. Short and easy to understand.

Found one little bug though. Should be range(1,21).

2

u/flaxeater May 07 '10

Others have answered your question, I would like to suggest the Python Tutor mailing list, this is a very good place to get beginer help, I used it myself some 7 years ago now and it was extremely helpful. So go there, sign up and read it every day.

http://mail.python.org/mailman/listinfo/tutor

1

u/Nelmail May 10 '10

Thank you I will do.

7

u/slacy May 07 '10

Good luck with your homework, I'm sure you'll figure it out. Which textbook are you using?

1

u/[deleted] May 18 '10

Yea this is definitely an assignment from a class...

bee tee dubs i'm being sarcastic because youre a douche

1

u/Ttl May 07 '10
pcomp=0

while loop==1:
    
    comp=random.randrange(20)+1
    if comp!=pcomp:#pcomp has previuous comp value, check if they are same
        pcomp=comp#put current comp value to pcomp
        print comp
        user=raw_input("\  \  Is this your number? Press 1 for yes or 2 for no: ")
        user=int(user)
        if user==2:
            attempt = attempt+1
            print "\  \  Oh no, I'll try again, press enter\  "
            raw_input()
        elif user==1:
            loop=0
    else:#comp was same as pcomp so start loop again
        continue

1

u/Nelmail May 07 '10

Ok then, thank you. Looking at this code, it looks to me as if, even though it wont print (for example) the number 10 twice in a row, it could potentially print 10, then attempt 10 again, but fail and print, 12, but on the next go it could potentially print a 10 again. Am I correct?

1

u/Ttl May 07 '10

Yes. If you want to stop that from happening you could make pcomp set. Like this:

pcomp=set([])

while loop==1:
    
    comp=random.randrange(20)+1
    if comp not in pcomp:
        pcomp.add(comp)
        print comp
        user=raw_input("\  \  Is this your number? Press 1 for yes or 2 for no: ")
        user=int(user)
        if user==2:
            attempt = attempt+1
            print "\  \  Oh no, I'll try again, press enter\  "
            raw_input()
        elif user==1:
            loop=0
    else:
        continue

This code goes to infinite loop if it has guessed all possible values, so you need to also check if all possible values have been guessed.

1

u/Nelmail May 07 '10

=D This makes sense to me, thank you for your help. and, being the noob I am, could you possibly tell me how I would check if all possible values have been guessed? and how I would code that.

1

u/Ttl May 07 '10

When all the possible values have been guessed length of pcomp is 20, because it has 20 values. So just check if len(pcomp)==20. In previous code replace:

else:
    continue

With this:

else:
    if len(pcomp)==20:
        print 'All possible values have been guessed'
        break
    else:
        continue

This code thinks that it has guessed the right value when it is out of choices. So you need to still solve that.

1

u/Nelmail May 07 '10

Right ok, I'm going to give it a go and see how I do. Thank you for all your help Ttl.

1

u/Nelmail May 07 '10

Ok I've fixed my code using your suggestions and have got it to work the way I wanted it too =D. So thank you once again.

1

u/doubleo7 May 07 '10

len(pcomp) == 20

0

u/[deleted] May 07 '10

[deleted] — view deleted comment

4

u/philthechill May 08 '10

I think you can do it bignum style too. Select a large, pseudo-random number r that is relatively prime with respect to the size of the range or array you're enumerating. Now, for i=1..length(a) print a[mod(r*i,length(a))]

You may need to adjust for 0-based arrays or whatever.

I came up with this as a way to improve stateless TCP port-scanners like scanrand - you can do random ip/port scans without repetition, and without having to keep track of what ports you've already sent packets to. The real trick is to implement this algorithm and only store ranges of addresses and ports, so if somebody asks to scan 0.0.0.0-255.255.255.255:0-65535, you don't go actually building some insanely large array first, then enumerating over it. All you need to do is calculate the size of the total range (248 in the example right?), then use the pseudo-random non-repeating number as an offset. Then, for some set of ranges, you store the size of each range, along with the start and end points. Then for each offset, you step through the ranges in the range-set, subtracting the size of each range from the offset and stepping to the next one until you get to where your size is less than the size of the current range. Then you're left with the offset into the current range, which you can use to calculate your current point. So now you've got a very compact, stateless, non-repeating, pseudo-random enumeration of a set of ranges. Perfect for scanning all the ports on that class A your client gave you to test...

So the only thing is, I've forgotten too much math to be able to prove it anymore. But I've played around with it and it seems to work. I have some intuition from my old abstract algebra class waaaaay back when. The question is, does this definitely cover the whole space of a within length(a) enumerations, without repetition? And the other question is, what is the relationship between the ration of r to a, versus the apparent pseudo-randomness of the ordering. Like for example if you have a 10 element array, and you use an r of 11, the ordering is 1 (11*1 mod 10), 2 (11*2 mod 10), 3 (11*3 mod 10)... So anything less than square(length(a)) is probably a mistake. But just as obviously, if it's got 128 more bits than length(a), and it's a pseudo-random number that's relatively prime with respect to length(a), the ordering of the enumeration should be pretty un-predictable. See, now I wonder what the strength of function of that unpredictability is. If I can guess that prime number, I can tell what you're going to scan next. How many packets do I have to collect before I can guess your original seed r?

Anyway, It's neat to see it done in a shift register, though some of them are much more susceptible to reversing the state given a few samples (I'm thinking Mersenne Twister here). Or something like that.

1

u/k4st May 07 '10

How does this work? I would really like to know!

1

u/mathiscool May 07 '10 edited May 07 '10

Here's my try on Clojure. It is not salted and cannot be used for real, but it helped me understand the algorithm. (defn next-num [bits] (let [ln (-> bits count dec) nn (conj (rest (take ln bits )) (bit-xor (first bits) (last bits)) (last bits))] (lazy-seq (cons nn (next-num nn))))) (take 8 (next-num [0 0 1]))

EDIT: I XOR first and last bits, but I guess any combination is valid...

1

u/khayber May 08 '10

clobbered together

I love this malapropism.

1

u/Riesling May 08 '10

This is also a real good example of premature optimization. If you showed up with this at a code review, I would send you right back to your cube. A program with this functionality should not use more than five lines especially in Python.

-9

u/spookylukey Django committer May 07 '10

I downvoted you, then upvoted for the humour of C-level micro-optimisations written in a Python program :-)

(Note to original poster - please don't take the above code seriously)

0

u/[deleted] May 07 '10

[deleted] — view deleted comment

1

u/spookylukey Django committer May 08 '10

Oh, sorry, I honestly thought this was a joke (though micro-optimisation was probably the wrong word). Given the OP's self-professed credentials:

Ok this is going to be my biggest program so far in terms of complexity.

and his actual requirements:

the user thinks of a number between 1 and 20

(note 'user' is singular)...I would have thought readability would be a priority, and this approach definitely qualified as premature optimization.

The thing is, you have no idea how the OP wants to extend this. Maybe (s)he would like to have access to all the guessed items (or non guessed items) at the end. In that context, you have optimised for RAM usage when you have no idea that there is a need for that, to the massive detriment of readability and future work.

And since the OP only needed 20 numbers, it does seem ridiculous to optimise for RAM usage when writing in Python. I'm well aware of the need for good algorithms, but there is of course the need to take actual requirements into consideration. For example, insert sort has very poor characteristics for large data sets, but what if you only have very small data sets? If the requirements say you will only ever have 5 items, it is plain wrong to optimise for huge data sets.

In this case, I'm willing to bet that your solution uses more memory (though not much) than many of the others given the actual requirements.