Generate Random List of Integers

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ss30
    New Member
    • Aug 2008
    • 6

    Generate Random List of Integers

    Hi,

    I'm really new to python or really any programming at all. I'm trying to write a game and I'm really stuck on one small, seemingly easy task.

    I have to generate a random list of n single digit integers (0 to 9).

    For example, ['1', '5', '2', '8'] where n is 4.

    Please help! I'm going out of my mind!

    Thanks heaps
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Have you attempted to write any code? Hint: random.randrang e() may be ideal for this task.

    Comment

    • ss30
      New Member
      • Aug 2008
      • 6

      #3
      so far i have used

      random.sample(r ange(0, 10), n) where n is the number of digits long.

      This works really well for getting a random list with no repeats, but i need to have a random list where repeats are allowed.

      Comment

      • boxfish
        Recognized Expert Contributor
        • Mar 2008
        • 469

        #4
        Hi,
        You can use a for loop to loop n times, appending random numbers to your list. Is that what you want?
        Hope this helps.

        Comment

        • ss30
          New Member
          • Aug 2008
          • 6

          #5
          Originally posted by boxfish
          Hi,
          You can use a for loop to loop n times, appending random numbers to your list. Is that what you want?
          Hope this helps.

          Yes, thankyou :) That helped a lot. I ended up using a while loop, but it seems to work well.

          Thanks!

          Comment

          • bvdet
            Recognized Expert Specialist
            • Oct 2006
            • 2851

            #6
            Originally posted by ss30
            Yes, thankyou :) That helped a lot. I ended up using a while loop, but it seems to work well.

            Thanks!
            ss30,

            The following uses a for loop and range() in a list comprehension to return a list of random integers:
            [code=Python]def random_ints(num , lower=0, upper=9):
            return [random.randrang e(lower,upper+1 ) for i in range(num)]

            print random_ints(4)[/code]This is the equivalent code without the list comprehension:[code=Python]def random_ints(num , lower=0, upper=9):
            ints = []
            for i in range(num):
            ints.append(ran dom.randrange(l ower,upper+1))
            return ints[/code]

            Comment

            Working...