Fun with fancy slicing

Ian McMeans imcmeans at telus.net
Sat Oct 4 22:17:49 EDT 2003


I've got to drop in my two cents :)
I wanted to see how clean I could make the algorithms look.

def quicksort(lst): 
     if len(lst) <= 1: return lst 
      
     left =   [x for x in lst if x <  lst[0]] 
     middle = [x for x in lst if x == lst[0]] 
     right =  [x for x in lst if x >  lst[0]] 

     return quicksort(left) + middle + quicksort(right)

>>> quicksort([random.randint(0, 20) for dummy in range(20)])
[0, 1, 2, 4, 4, 4, 4, 4, 6, 6, 8, 9, 12, 12, 13, 14, 14, 14, 16, 16]

Hopefully this is still nlogn :)

and then:

def primes(): 
     p = {} 
     for cand in itertools.count(2): 
         if not [True for factor in p if not cand % factor]: 
             p[cand] = None
             yield cand

list(itertools.islice(primes(), 0, 20))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]




More information about the Python-list mailing list