開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc., Emacs(Text Editor)
- プログラミング言語: Python
『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7)のIV部(クラスとオブジェクト指向プログラミング)、まとめ演習5.(Setクラス)を解いてみる。
その他参考書籍
まとめ演習5.(Setクラス)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
class Set:
def __init__(self, value = []):
self.data = []
self.concat(value)
def intersect(self, other):
res = []
for x in self.data:
if x in other:
res.append(x)
return Set(res)
def union(self, other):
res = self.data[:]
for x in other:
if not x in res:
res.append(x)
return Set(res)
def concat(self, value):
for x in value:
if not x in self.data:
self.data.append(x)
def __add__(self, other):
self.concat(other)
return Set(self.data)
def __len__(self): return len(self.data)
def __getitem__(self, key): return self.data[key]
def __and__(self, other): return self.intersect(other)
def __or__(self, other): return self.union(other)
def __repr__(self): return 'Set: {0}'.format(self.data)
def __getattr__(self, attrname): # 処理を委託(デリゲーション)
return getattr(self.data, attrname)
class SetSub(Set):
def intersect(self, *others):
res = []
for x in self.data:
for other in others:
if not x in other:
break
else:
res.append(x)
return SetSub(res)
def union(self, *others):
res = self.data[:]
for other in others:
for x in other:
if not x in res:
res.append(x)
return SetSub(res)
if __name__ == '__main__':
s1 = Set([1,2,3,4,5])
s2 = Set([2,4,6,8,10])
print("s1 {0}, s2 {1}".format(s1, s2))
print("& {0}".format(s1 & s2))
print("| {0}".format(s1 | s2))
s1 = Set("abcde")
print("s1 {0}".format(s1))
print("s1[0] {0}".format(s1[1])) # __getitem__が呼び出される
for c in s1:
print(c)
s2 = "defghijklmn"
print("s2 {0}".format(s2))
try:
print("& {0}".format(s1 & s2))
except Exception as err:
print(type(err), err)
try:
print("| {0}".format(s1 | s2))
except Exception as err:
print(type(err), err)
s1 = SetSub([1,2,3,4,5])
s2 = SetSub([6,7,8,9,10])
even = SetSub([2,4,6,8,10])
odd = SetSub([1,3,5,7,9])
s = SetSub([1, 2, 8, 10, 12, 14, 16])
print(s1.intersect(even, s))
print(s1.union(s2, even, odd, s))
s1 = Set([1,2,3,4,5])
s2 = Set([2,4,6,8,10])
print(s1 + s2)
s1.clear()
print(s1)
print(s2.index(4))
print(s2.pop())
print(s2)
入出力結果(Terminal)
$ ./sample.py s1 Set: [1, 2, 3, 4, 5], s2 Set: [2, 4, 6, 8, 10] & Set: [2, 4] | Set: [1, 2, 3, 4, 5, 6, 8, 10] s1 Set: ['a', 'b', 'c', 'd', 'e'] s1[0] b a b c d e s2 defghijklmn & Set: ['d', 'e'] | Set: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n'] Set: [2] Set: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16] Set: [1, 2, 3, 4, 5, 6, 8, 10] Set: [] 1 10 Set: [2, 4, 6, 8] $
0 コメント:
コメントを投稿