Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1c8ea28

Browse files
authored
Update recipe-576917.py
included a lambda version (<2.7?) and added a >3.5x version as well.
1 parent 3855ec8 commit 1c8ea28

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

recipes/Python/576917_Functional_selection_sort/recipe-576917.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,33 @@
1616
print test_list
1717
print selection_sort(test_list)
1818

19+
1920
# Recursive version
2021
def select_sort_r(L):
2122
if not L: return [] # terminal case
2223
v, idx = min((v, i) for i, v in enumerate(L)) # select the smallest
2324
return [v] + select_sort_r(L[:idx] + L[idx+1:]) # recursively call on the remainder
25+
26+
27+
# Lambda version
28+
# Python > 2.7.10 and above
29+
select_sort_l = (
30+
lambda L: [] if not L else (
31+
lambda idx, v: [v] + select_sort_l(L[:idx] + L[idx + 1:]))(
32+
*min(enumerate(L), key=lambda t: t[1])
33+
)
34+
)
35+
36+
# OP's version from the comments, works probably for Python < 2.7.10
37+
selsort2 = (lambda l: [] if not l else
38+
(lambda (idx, v): [v] + selsort2(l[:idx] + l[idx + 1:]))
39+
(min(enumerate(l), key=lambda(i, x): x)))
40+
41+
42+
# OP's original test_list gets mutated by the functional version
43+
test_list = [5, 1, 7, 0, -3, -10, 10, -6, 1, 0, 2, 4, -2, 6, 5, 8, 2]
44+
expected = [-10, -6, -3, -2, 0, 0, 1, 1, 2, 2, 4, 5, 5, 6, 7, 8, 10]
45+
46+
assert select_sort_r(test_list) == expected
47+
assert select_sort_l(test_list) == expected
48+
# assert selsort2(test_list) == expected

0 commit comments

Comments
 (0)