[Tutor] Re: Recursive list checking

Jeffrey Maitland maitj at vianet.ca
Fri Apr 8 18:11:38 CEST 2005


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 



More information about the Tutor mailing list