Re: Fun with fancy slicing
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 )
[color=blue][color=green][color=darkred]
>>> quicksort([random.randint( 0, 20) for dummy in range(20)])[/color][/color][/color]
[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]
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 )
[color=blue][color=green][color=darkred]
>>> quicksort([random.randint( 0, 20) for dummy in range(20)])[/color][/color][/color]
[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]
Comment