[Tutor] Recursive list checking

Rick Muller rmuller at sandia.gov
Fri Apr 8 20:54:15 CEST 2005


On Apr 8, 2005, at 11:37 AM, tutor-request at python.org wrote:
> From: joe_schmoe <geek_show at dsl.pipex.com>
> 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 )
>
> ================================================
>

Since you want unique entries, couldn't you just do something like

def unique_entries(n,start=1,stop=20):
     "Generate n unique entries in range(1,20)"
     from random import shuffle
     l = range(start,stop)
     shuffle(l)
     return l[:n]




More information about the Tutor mailing list