Random Number Generator in Python

Discussion in 'Scripting & Programming' started by tripwire45, Mar 20, 2008.

  1. tripwire45
    Honorary Member

    tripwire45 Zettabyte Poster

    13,493
    180
    287
    I had more than a passing reason to ask about modules recently. They are actually part of my homework assignment (as are dictionaries, but I'm coming to that).

    The assignment was to re-write a previous example so that the user running the program has to guess a number and that number is "randomly" (not really random, of course) generated by the time module...specifically, the last two digits generated.

    I tried to approach this problem head on but couldn't find the solution. I decided to "sneak up on it" instead and by using both the time and datetime modules as follows:
    Code:
    # Uses how many days it is in the current year as of today 
    # as a random number for the user to guess
    # As in "today is the 78 day of the current year".
    import time
    import datetime
    number = time.localtime()[7]
    guess = 0
    while guess != number :
        guess = input ("Guess a number: ")
        if guess > number :
            print "Too high"
        elif guess < number :
                print "Too low"
    print "Just right"
    This program basically does what the exercise wants it to do in that it uses the output from a module to generate a "random" number for the user to guess. In this case, this number only changes once per day and so is far too easy to guess...but it's a start and shows me I can actually create something that works in principle.

    The following code is "sort of" the solution, but I have a problem as you'll see:
    Code:
    # Uses the value generated by time.time(), 
    # such as "1205980124.59", as the random number to guess.
    # How can I use just the last two digits (such as "59") as the random number?
    # Can a dictionary and one or more lists be used to create the solution?
    import time
    number = time.time()
    guess = 0
    while guess != number :
        guess = input ("Guess a number: ")
        if guess > number :
            print "Too high"
        elif guess < number :
                print "Too low"
    print "Just right"
    I need to pull out only the last two digits of the output and have them used as the "random" number. Unfortunately, I can't see how to do that. Since the sections leading up to this assignment are on dictionaries and modules, I figure somehow, dictionaries and lists must be part of the solution. I can't see how though...even after scouring the Internet (yes I know, "Google is your friend", but it's not all *that* friendly).

    Just when you thought it was safe to enter this forum again. :wink:

    As always, help is appreciated. Thanks.
     
    Certifications: A+ and Network+
  2. Fergal1982

    Fergal1982 Petabyte Poster

    4,196
    172
    211
    Dont you use Seed and Randint to generate random numbers in python? Thats how its done in VB(Script and .Net) - well, not specifically the same, but you initialise the random number generator and pull out random numbers from it.

    Found This
    And This
     
    Certifications: ITIL Foundation; MCTS: Visual Studio Team Foundation Server 2010, Administration
    WIP: None at present
  3. dmarsh
    Honorary Member 500 Likes Award

    dmarsh Petabyte Poster

    4,305
    503
    259
    Its an interesting topic, since computers are not really capable of being 'random', they are deterministic machines.

    Theres various ways they can generate pseudo random numbers or sequences and these are normally tested for randomness using the chi square test.

    Common methods include time, modulo 7 arithmetic and even entropy chips !

    Pseudorandom number generator

    Basic Generator

    You might want to read what Donald Knuth has to say about the subject.
    Knuth Source in C

    All of this is normally hidden behind a standard library function called something like rand...

    http://www2.informatik.hu-berlin.de/Themen/manuals/python/python-texinfo/rand.html

    As with many things a really good implementation of a good algorithm is very important, as otherwise your random numbers aren't random at all and are certainly no good for computer based research. This is why its normally left to library writers or experts in the field. Thats why modules exist ! :D
     
  4. Tinus1959

    Tinus1959 Gigabyte Poster

    1,539
    42
    106
    If you need to specifically use this time.time function, you might want to try to substract the integer of the result from the result itself.
     
    Certifications: See my signature
    WIP: MCSD, MCAD, CCNA, CCNP
  5. hbroomhall

    hbroomhall Petabyte Poster Gold Member

    6,624
    117
    224
    Why not use the time() function, use the result as a string and cut the last two characters from that string?

    BTW - versions of that time module appear in almost every language, as it is based on a standard part of the C libraries.

    Edit: Oops - I didn't read to the end of your post! Look up 'slice'.

    Harry.
     
    Certifications: ECDL A+ Network+ i-Net+
    WIP: Server+
  6. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    The time module in Python makes use of Epoc/Unix time, if I recall correctly. Look into the various formats presented and determine the best for the task at hand. hbroomhall is along the right lines, but you don't need to go through the bother of string manipulations.

    Am interested to see how this turns out. :)
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  7. tripwire45
    Honorary Member

    tripwire45 Zettabyte Poster

    13,493
    180
    287
    Ok, it's come down to this. I need to modify the following so that it only prints the two digits after the decimal point:
    Code:
    import time
    
    now = time.time()
    
    print now
    As it stands now, whenever, I run this, I come up with values such as 1206316347.51 or 1206316349.23 or 1206316350.82. I've searched more websites than I can count but feel like I've been pursuing dead ends. I thought I was on to something when I tried (please don't laugh):
    Code:
    import time
    
    now = time.time()
    
    print now (format="%S")
    when it produced an actual message:
    Code:
        print now (format="%S")
    TypeError: 'float' object is not callable
    jmpyles@lamp:~/python$
    
    instead of just a syntax error. Yes, the assignment does call for me to use the last two digits of the output from the module to generate the so-called "random number". I can't find a format that will produce just those two digits in the first place (wouldn't that be sweet).

    Ideas?
     
    Certifications: A+ and Network+
  8. tripwire45
    Honorary Member

    tripwire45 Zettabyte Poster

    13,493
    180
    287
    Nevermind. I got the answer. It all has to do with using the correct attribute of the time module. As you'll recall, the following produces the day since January 1st as the number using the tm_yday attribute:
    Code:
    import time
    import datetime
    number = time.localtime()[7]
    guess = 0
    while guess != number :
        guess = input ("Guess a number: ")
        if guess > number :
            print "Too high"
        elif guess < number :
                print "Too low"
    print "Just right"
    I finally figured it out when I visited this page:

    http://docs.python.org/lib/module-time.html

    Scroll down until you see the three column table with columns for Index, Attribute, and Values. the value in square brackets for number = time.localtime() is referencing the tm_yday. All I had to do is change that value from a "7" to a "5" to reference the tm_sec (seconds) attribute. Here's the proof:
    Code:
    import time
    import datetime
    number = time.localtime()[5]
    
    print number
    If you run that program, it will print whatever the seconds happens to be from the localtime of your PC at the moment the program is run.

    I think I got this one, folks. :biggrin
     
    Certifications: A+ and Network+
  9. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    Awesome, trip! Welcome to the world of programming and having to solve problems in complete isolation.

    I bet the past problems look quite easy now. :biggrin
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.
  10. tripwire45
    Honorary Member

    tripwire45 Zettabyte Poster

    13,493
    180
    287
    Well...easier, anyway. Thanks for being patient. I imagine my stumbling about with these elementary problems looks pretty silly to someone with programming experience. Hopefully, it'll start getting a bit easier or at least, I'll start learning how to solve more "adult" type problems.
     
    Certifications: A+ and Network+
  11. Mathematix

    Mathematix Megabyte Poster

    969
    35
    74
    Nah, nothing anyone ever looks silly. I can still barely remember when I had no programming skill whatsoever. As they say, we weren't born knowing how to program!

    Remember to take it easy, though, as everyone learns programming at their own pace. :)
     
    Certifications: BSc(Hons) Comp Sci, BCS Award of Merit
    WIP: Not doing certs. Computer geek.

Share This Page

Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.