前回のStrategyパターン
http://ksk77.blogspot.com/2010/11/10-strategy.html
で、練習問題に挙げられていた『ソートアルゴリズムを切り替えられるソータクラス』をpythonで書いてみた。
選択ソート、クイックソートだけです。間違ってたらごめんなさい。
実行結果
Dumpty, Bowman, Carroll, Elfland, Alice Alice, Bowman, Carroll, Dumpty, Elfland Dumpty, Bowman, Carroll, Elfland, Alice Alice, Bowman, Carroll, Dumpty, Elfland 4, 6, 2, 4, 7, 0, 1, 12 0, 1, 2, 4, 4, 6, 7, 12 4, 6, 2, 4, 7, 0, 1, 12 0, 1, 2, 4, 4, 6, 7, 12
ソースコード
sorter.py
# -*- coding: utf8 -*-
class __Sorter:
def __init__(self): raise NotImplementedError
def sort(self, data): raise NotImplementedError
class SelectionSorter(__Sorter):
def __init__(self): pass
def sort(self, data):
if len(data) <= 1: return data
minx = data.pop(data.index(min(data)))
return [minx] + self.sort(data)
class QuickSorter(__Sorter):
def __init__(self): pass
def sort(self, data):
return self.sort(filter(lambda x: x < data[0], data)) + filter(lambda x: x == data[0], data) + self.sort(filter(lambda x: x > data[0], data)) if len(data) > 1 else data
from copy import copy
class SortAndPrint:
def __init__(self, data, sorter):
self.data = data
self.sorter = sorter
def execute(self):
self.__draw(self.data)
sorted_data = self.sorter.sort(copy(self.data))
self.__draw(sorted_data)
def __draw(self, d):
print ", ".join(map(str, d))
main.py
#!/usr/bin/env python
# -*- coding: utf8 -*-
from sorter import SortAndPrint, SelectionSorter, QuickSorter
def main():
data = ["Dumpty", "Bowman", "Carroll", "Elfland", "Alice"]
sap = SortAndPrint(data, SelectionSorter())
sap.execute()
sap = SortAndPrint(data, QuickSorter())
sap.execute()
data = [4,6,2,4,7,0,1,12]
sap = SortAndPrint(data, SelectionSorter())
sap.execute()
sap = SortAndPrint(data, QuickSorter())
sap.execute()
if __name__=='__main__': main()
0 件のコメント:
コメントを投稿