0

I've been trying to solve this problem. I would like to input a number between 1 and 5. So for example if I choose to input number 3, I want to then randomly choose 3 numbers from a category of numbers between 1 and 10.

5
  • 1
    Keep in mind that a computer cannot generate really random numbers. It can only generate what are called pseudo-random numbers. Read docs.python.org/library/random.html and en.wikipedia.org/wiki/Random_number_generation. It depends on the application if the numbers generated by the random module are suitable. Commented Aug 22, 2012 at 8:12
  • Should the numbers be unique? Also, have you got any code so far? Commented Aug 22, 2012 at 8:37
  • what have you tried? If you post your attempt (however minimal), it helps others in guiding you correctly. Commented Aug 22, 2012 at 8:41
  • Im gonna try and post what I have so far. Commented Aug 23, 2012 at 4:49
  • 1
    Never mind, the answer I was looking for is at the bottom of this page. Commented Aug 23, 2012 at 5:05

4 Answers 4

0
import random
random.seed()
a = 1
b = 10
randList = []
for x in range(3):
    # random integer N such that a <= N <= b
    randList.append(random.randint(a, b))

Or better yet:

import random
random.seed()
a = 1
b = 10
randList = [random.randint(a,b) for x in range(3)]
Sign up to request clarification or add additional context in comments.

1 Comment

You probably want to seed() the random number generator first.
0

A simple approach:

from random import choice
list_of_numbers = range(11)[1:] # the 1: drops the zero
choice(list_of_numbers) # picks a random number from the list

2 Comments

just for information ... you can also do list_of_numbers = range(1,11) instead of slicing the list after range
Nice! I've never used choice before. Good addition to the belt.
0
myrands = [rand_int(1,10) for x in range(0,int(raw_input()))]

myrands is a list of random numbers between 1 and 10, the length is determined by user input.

Comments

-1

something of this sort could work...

In [84]: user_input = raw_input("Enter a number between 1 to 5 :")
Enter a number between 1 to 5 :3

In [85]: selected_elem = []

In [86]: while len(selected_elem) < int(user_input):
   ....:         random_elem = random.randrange(1, 10, 1)
   ....:         if random_elem not in selected_elem:
   ....:                 selected_elem.append(random_elem)
   ....:

In [87]: print selected_elem
[1, 2, 4]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.