Welcome, guest | Sign In | My Account | Store | Cart

Picks a number of unique random elements from a list.

Python, 58 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
##################################################################################
##
##	Author:		Premshree Pillai
##	Date:		15/07/03	
##	File Name:	urn.py
##	Description:    -Unique Random Numbers
##                      -Returns a list of specified number of elements from
##                       another list such that each element in the returned
##                       list is unique and random.
##                       See e.g. below.
##	Website:	http://www.qiksearch.com
##
##################################################################################

from random import Random

def pickNums(nums, numArr):
    if(nums > len(numArr)):
        return 0
    pickArr = []
    tempArr = numArr
    i = 0
    while(i < nums):
        g = Random()
        pickArr.append(tempArr[int(round((len(tempArr) - 1) * g.random()))])
        temp = pickArr[len(pickArr)-1]
        count = 0
        for x in tempArr:
            if(x == temp):
                tempArr[count] = 'null'
                tempArr2 = []
                for y in tempArr:
                        if(y != 'null'):
                                tempArr2.append(y)
                tempArr=tempArr2;
                break
            count = count + 1
        i = i + 1
    return pickArr

##
## Create a list
##
myArr = ['1','2','3','4','5','6','7']

##
## The following function call will return a 2-element list, the elements
## of which are derived from myArr. The elements of the returned
## list (say, retArr) are such that each is unique. i.e. if  
## retArr[i] = myArr[j] then no other element of retArr will
## be equal to myArr[j]
##
print pickNums(2,myArr)

##
## You may also call the function like this:
##    
print pickNums(2,['1','2','3','4','5','6','7'])

This script illustrates how to pick a set of unique, random elements from a given list.

3 comments

Anand 18 years, 1 month ago  # | flag

Err, too much trouble? If the idea is to return a list containing unique

random elements of the passed list, this code

does the same, albeit in much fewer lines.

def pickNums2(nums, numArr):

    if (nums > len(numArr)):
        return -1

    Random().shuffle(numArr)
    return numArr[:nums]

print pickNums2(2, [1,2,3,4,5,6,7,8,9,10])

Maybe I am missing something here. Then correct me.

-Anand

Raymond Hettinger 18 years ago  # | flag

For Py2.3, this function is already built in. >>> random.sample(['1','2','3','4','5','6','7'], 2) ['2', '5']

jelle feringa 16 years, 8 months ago  # | flag

not recommended. this script doesnt do a decend job in selecting random numbers, and like Raymond points out, is redundant. Also a highly inefficient way of doing this. Can we loose it?