I need some help, how to use the algorithm selection sort to sort a list by the values of a dict. I wrote some code but I don’t know how continue, that the code work.
JavaScript
x
4
1
months = {"January": 1, "February": 2, "March": 3, "April": 4, "May": 5, "June": 6, "July": 7, "August": 8, "September": 9, "October": 10, "November": 11, "December": 12}
2
3
L = ["March", "January", "December"]
4
e.g. sort the list by the values of the dict
JavaScript
1
11
11
1
def month(L):
2
for i in months:
3
minpos = i
4
for j in range (months[i], len(L)):
5
if months[L[j]] > months[minpos]:
6
months[minpos] = months[L[j]]
7
8
L[j], L[minpos] = L[minpos], L[i]
9
10
return L
11
Advertisement
Answer
New Answer
- Create class
selection_sort
which hasget_sorted()
method that will sort the list based on dictionary values using selection sort. - Here we compare two value and if first value is greater than second, than swap both the values. Repeat this step until entire list is sorted.
JavaScript
1
26
26
1
class selection_sort:
2
"""Sort the list based on dictionary value using selection sort."""
3
def __init__(self,L):
4
self.months = {"January": 1, "February": 2, "March": 3, "April": 4,
5
"May": 5,
6
"June": 6, "July": 7, "August": 8, "September": 9,
7
"October": 10, "November": 11, "December": 12}
8
self.L = L
9
10
def get_sorted(self):
11
""" sorting list."""
12
month_num = [self.months[i] for i in self.L]
13
flag = True # set Flag is True to enter the loop.
14
while flag:
15
flag = False # set Flag to False for no swaping done
16
17
for i in range(len(month_num)-1):
18
if month_num[i] > month_num[i+1]:
19
flag = True # set Flag to False if no swaping is done
20
# swap
21
month_num[i], month_num[i+1] = month_num[i+1], month_num[i]
22
23
L = [k for k, v in self.months.items() if v in month_num]
24
print(L)
25
return L
26
Test Case
Test which you have written is comparing
L
withExpected
. It should compareactual
withexpected
.self.assertEqual(L, expected)
Also, expected =
["March", "May", "December", "October", "September"]
is incorrect. It should have been["March", "May","September", "October", "December"]
JavaScript
1
12
12
1
import unittest
2
from selectionSort import selection_sort
3
4
# @unittest.skip("")
5
class TestInPlace(unittest.TestCase):
6
def test_1(self):
7
L = ["December", "September", "March", "October", "May"]
8
obj = selection_sort(L)
9
actual = obj.get_sorted()
10
expected = ["March", "May","September", "October", "December"]
11
self.assertEqual(actual, expected)
12
Old Answer
Try this,
JavaScript
1
15
15
1
#creating list L1
2
L1 = [months[L[i]] for i in range(len(L))]
3
print(L1)
4
5
#sorting list using algorithm selection sort
6
for i in range(1,len(L1)):
7
j = 0
8
if L1[j] > L1[i] :
9
L1[j], L1[i] = L1[i] ,L1[j]
10
print(L1)
11
12
#Replacing values with key
13
sorted_list = [ k for k,v in months.items() for i in L1 if i == v]
14
print(sorted_list)
15