[Tutor] Re: Recursive list checking
Kent Johnson
kent37 at tds.net
Fri Apr 8 19:26:30 CEST 2005
Jeffrey Maitland wrote:
> joe_schmoe writes:
>
>> Dear Pythonites
>> I am looking for a more elegant solution to a piece of code that is
>> too unwieldy and reptitive. The purpose of the code is for a new
>> addition to a list to check whether it is a duplicate of a list
>> element already a member of that list, and if so to regenerate itself
>> randomly and to perform the same check again until such time as it is
>> unique.
>> For example, this is what I am currently doing:
>> =============code block ========================
>> # generate unique numbers and append to list
>> nmbr01 = random.randrange( 1, 20 )
>> nmbr_list.append( nmbr01 )
>> nmbr02 = random.randrange( 1, 20 )
>> # check for duplicates and re-generate a number if needed
>> while nmbr02 in nmbr_list:
>> nmbr02 = random.randrange( 1, 20 )
>> nmbr_list.append( nmbr02 )
>> nmbr03 = random.randrange( 1, 20 )
>> while nmbr03 in nmbr_list:
>> nmbr03 = random.randrange( 1, 20 )
>> nmbr.append( nmbr03 )
>> ================================================
>> This method works, but increasing the numbers to be appended makes the
>> code excessively long. I can't see anything in list methods that seems
>> to do the trick, so anybody want to make a suggestion please?
>> TIA
>> /j
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>
>
> Well I would start by doing something like.
> nmbr_list = []
> value = int(raw_input("Input the number of items you wish to generate"))
> for i in range(value):
> if i == 0:
> nmbr = random.randrange( 1, 20 )
> nmbr_list.append( nmbr01 )
> else:
> nmbr = random.randrange( 1, 20 )
> # check for duplicates and re-generate a number if needed
> while nmbr in nmbr_list:
> nmbr = random.randrange( 1, 20 )
> nmbr_list.append( nmbr )
> I hope that helps. or gives you an idea.
The special case for i==0 is not needed, in this case the test for nmbr in nmbr_list will fail and
nmbr will be added to the list.
But if you are trying to get n random elements from range(m) you are probably better off using
random.sample(), I think it does exactly what you want:
>>> random.sample(xrange(10000000), 10)
[274075, 2925710, 7715591, 8236811, 1161108, 5804222, 2385884, 9236087, 5603149, 8473299]
If you actually want *all* elements of the range in random order, use random.shuffle():
>>> l=range(20)
>>> random.shuffle(l)
>>> l
[13, 7, 6, 9, 3, 10, 1, 8, 4, 0, 18, 12, 11, 17, 19, 5, 16, 15, 2, 14]
You might also want to look at random.choice()...
Kent
More information about the Tutor
mailing list