Created
October 26, 2020 02:55
-
-
Save EvanMu96/2d98108c03a2cc887c040632746d51d8 to your computer and use it in GitHub Desktop.
remove all of the for loops
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def ascending(a, b): return a - b | |
def descending(a, b): return -ascending(a, b) | |
# selection sort | |
def sorted(xs, compare = ascending): | |
return [] if not xs else __select(xs, compare) | |
def __select(xs, compare): | |
selected = xs[0] | |
for elem in xs[1:]: | |
if compare(elem, selected) < 0: | |
selected = elem | |
remain = [] | |
selected_list = [] | |
for elem in xs: | |
if elem != selected: | |
remain.append(elem) | |
else: | |
selected_list.append(elem) | |
return xs if not remain else selected_list + __select(remain, compare) | |
print(sorted([2, 1, 3, 6, 5])) | |
print(sorted([2, 1, 3, 6, 5], descending)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment