When I read the haskell book, I remembered opening my eyes to scala and wanted to write a recursive function, but I wasn't confident, so I put up with qsort. I want to write a cooler recursion by sticking the recursion properly to the registry in the brain. Whenever I wrote a loop, I thought it would be good to imagine what would happen if I wrote it recursively.
qsort.py
import random
a = [i for i in range(100)]
random.shuffle(a)
print "before"
print a
def qsort(l):
if len(l) > 1:
pivot = random.randrange(len(l))
smaller = [i for i in l if i < l[pivot] ]
bigger = [i for i in l if i >= l[pivot] ]
l = qsort(smaller) + qsort(bigger)
return l
a = qsort(a)
print "after"
print a
```##Output result
before
[5, 40, 28, 72, 7, 68, 64, 91, 37, 67, 23, 90, 85, 43, 39, 93, 58, 62, 75, 41, 53, 14, 3, 52, 47, 94, 44, 15, 80, 99, 89, 56, 33, 84, 86, 70, 10, 61, 59, 76, 35, 1, 60, 96, 55, 19, 26, 24, 32, 97, 30, 57, 66, 25, 69, 98, 12, 42, 78, 27, 87, 51, 21, 82, 92, 71, 9, 95, 11, 6, 83, 2, 81, 73, 17, 63, 16, 46, 34, 22, 77, 4, 48, 79, 49, 88, 36, 65, 29, 50, 31, 8, 18, 54, 45, 38, 20, 0, 74, 13]
after
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
Recommended Posts