新答案
- 创建具有
get_sorted() 方法的类selection_sort,该方法将使用选择排序根据字典值对列表进行排序。
- 这里我们比较两个值,如果第一个值大于第二个值,则交换两个值。重复此步骤,直到对整个列表进行排序。
class selection_sort:
"""Sort the list based on dictionary value using selection sort."""
def __init__(self,L):
self.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}
self.L = L
def get_sorted(self):
""" sorting list."""
month_num = [self.months[i] for i in self.L]
flag = True # set Flag is True to enter the loop.
while flag:
flag = False # set Flag to False for no swaping done
for i in range(len(month_num)-1):
if month_num[i] > month_num[i+1]:
flag = True # set Flag to False if no swaping is done
# swap
month_num[i], month_num[i+1] = month_num[i+1], month_num[i]
L = [k for k, v in self.months.items() if v in month_num]
print(L)
return L
测试用例
-
您编写的测试是将L 与Expected 进行比较。它应该将actual 与expected 进行比较。 self.assertEqual(L, expected)
-
另外,预期 = ["March", "May", "December", "October", "September"] 不正确。应该是["March", "May","September", "October", "December"]
import unittest
from selectionSort import selection_sort
# @unittest.skip("")
class TestInPlace(unittest.TestCase):
def test_1(self):
L = ["December", "September", "March", "October", "May"]
obj = selection_sort(L)
actual = obj.get_sorted()
expected = ["March", "May","September", "October", "December"]
self.assertEqual(actual, expected)
旧答案
试试这个,
#creating list L1
L1 = [months[L[i]] for i in range(len(L))]
print(L1)
#sorting list using algorithm selection sort
for i in range(1,len(L1)):
j = 0
if L1[j] > L1[i] :
L1[j], L1[i] = L1[i] ,L1[j]
print(L1)
#Replacing values with key
sorted_list = [ k for k,v in months.items() for i in L1 if i == v]
print(sorted_list)