Skip to content Skip to sidebar Skip to footer

Choose Multiple Random Integers With Input

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

Solution 1:

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 randomrandom.seed()
a = 1
b = 10
randList = [random.randint(a,b) for x in range(3)]

Solution 2:

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

Solution 3:

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.

Solution 4:

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]

Post a Comment for "Choose Multiple Random Integers With Input"