Welcome, guest | Sign In | My Account | Store | Cart

This is a variant of selection sort without using for-statements. Do you like it? :-)

Python, 17 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
selection_sort = lambda sort_list: reduce(
    lambda my_list, i: (
        lambda max_value=reduce(
            lambda a, b: b if b > a else a,
            my_list[1]
        ): [
            my_list[1].remove(max_value),
            my_list[0].append(max_value)
        ] and  my_list
    )(),
    range(len(sort_list)),
    [[], sort_list]
)[0]

test_list = [ 5, 1, 7, 0, -3, -10, 10, -6, 1, 0, 2, 4, -2, 6, 5, 8, 2]
print test_list
print selection_sort(test_list)

1 comment

Matteo Dell'Amico 14 years, 7 months ago  # | flag

This is simpler and doesn't use the imperative constructs list.remove and list.append:

def selsort(l):
    if not l: return []
    idx, v = min(enumerate(l), key=operator.itemgetter(1))
    return [v] + selsort(l[:idx] + l[idx + 1:])

...or was it the challenge to have it all in a single expression?

selsort2 = (lambda l: [] if not l else
            (lambda (idx, v): [v] + selsort(l[:idx] + l[idx + 1:]))
            (min(enumerate(l), key=lambda(i, x): x)))
Created by pavel on Tue, 29 Sep 2009 (MIT)
Python recipes (4591)
pavel's recipes (5)

Required Modules

  • (none specified)

Other Information and Tasks