Skip to content

Instantly share code, notes, and snippets.

@EvanMu96
Created October 26, 2020 02:55
Show Gist options
  • Save EvanMu96/2d98108c03a2cc887c040632746d51d8 to your computer and use it in GitHub Desktop.
Save EvanMu96/2d98108c03a2cc887c040632746d51d8 to your computer and use it in GitHub Desktop.
remove all of the for loops
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