[Tutor] Re: Recursive list checking
Jeffrey Maitland
maitj at vianet.ca
Fri Apr 8 18:17:40 CEST 2005
Jeffrey Maitland writes:
> 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.
> Jeff
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
Err just noted that I screwed up on my idea.. here.. is a better party same
idea edited some.
nmbr_list = []
value = int(raw_input("Input the number of items you wish to generate"))
# so this loops the value specified times, as this will add that number to
list too. so a range of 1 - 20 in random order if 20 is the sepcified
number.
for i in range(value):
if i == 0:
nmbr = random.randrange( 1, value )
nmbr_list.append( nmbr )
else:
nmbr = random.randrange( 1, value )
# check for duplicates and re-generate a number if needed
while nmbr in nmbr_list:
nmbr = random.randrange( 1, value )
nmbr_list.append( nmbr )
Jeff
also feel free to ask me more speicifc questions via email if you think they
won't help the cominity at all.
More information about the Tutor
mailing list