Random number generator

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Thekid
    New Member
    • Feb 2007
    • 145

    Random number generator

    I've been playing with the random module but can't seem to get my code to print out more than one random number. How do I go about that? I 've tried several things but haven't figured it out yet.

    Code:
    from random import randint
    a = randint(0,40)
    print a
    or

    Code:
    import random
    print random.randrange(0,40,1)
    That works fine but how can I get it to print out 3 numbers? Example:

    3, 16, 23

    I did find this code below which works for this purpose but I figure there has to be an easier way:

    Code:
    # File: random-example-4.py
    
    import random
    
    try:
        # available in Python 2.0 and later
        shuffle = random.shuffle
    except AttributeError:
        def shuffle(x):
            for i in xrange(len(x)-1, 0, -1):
                # pick an element in x[:i+1] with which to exchange x[i]
                j = int(random.random() * (i+1))
                x[i], x[j] = x[j], x[i]
    
    cards = range(52)
    
    shuffle(cards)
    
    myhand = cards[:5]
    
    print myhand
  • kaarthikeyapreyan
    New Member
    • Apr 2007
    • 106

    #2
    Hey try this if it suits ur requirement
    I Have hardcoded 2 since u wanted only 3 numbers, modify it to ur need

    Code:
    import random
    randlist=[]
    while (randlist.__len__() <= 2):
      b =random.randint(0,25)
      if not b in randlist:
         randlist.append(b)
    print randlist

    Comment

    • Thekid
      New Member
      • Feb 2007
      • 145

      #3
      Originally posted by kaarthikeyaprey an
      Hey try this if it suits ur requirement
      I Have hardcoded 2 since u wanted only 3 numbers, modify it to ur need

      Code:
      import random
      randlist=[]
      while (randlist.__len__() <= 2):
        b =random.randint(0,25)
        if not b in randlist:
           randlist.append(b)
      print randlist
      Very nice, thank you!

      Comment

      Working...