開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc., Emacs(Text Editor)
- プログラミング言語: Python
『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のVI部(クラスとオブジェクト指向プログラミング)のまとめ演習5.(Setクラス)を解いてみる。
その他参考書籍
5.(Setクラス)
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
class Set(list):
def __init__(self, value = []):
list.__init__([])
self.concat(value)
def intersect(self, other):
res = []
for x in self:
if x in other:
res.append(x)
return Set(res)
def union(self, other):
res = Set(self)
res.concat(other)
return res
def concat(self, value):
for x in value:
if not x in self:
self.append(x)
def __and__(self, other): return self.intersect(other)
def __or__(self, other): return self.union(other)
def __repr__(self): return "Set: " + list.__repr__(self)
def __getattr__(self, name):
return getattr(self, name)
class SetSub(Set):
def intersect(self, *others):
res = []
for x in self:
for other in others:
if not x in other:
break
else:
res.append(x)
return Set(res)
def union(self, *others):
res = self
for other in others:
for x in other:
if not x in res:
res.append(x)
return Set(res)
if __name__ == '__main__':
x = Set([1,3,5,7])
y = Set([2,1,4,5,6])
print(x & y)
print(x | y)
chs = Set("python")
print(chs)
print(chs[1])
for ch in chs:
print(ch)
try:
print("共通部分", chs & "programming")
except Exception as err:
print(type(err), err, err.args)
try:
print("和集合",chs | "programming")
except Exception as err:
print(type(err), err, err.args)
x = SetSub([1,3,5,7])
y = SetSub([2,1,4,5,6])
z = SetSub([2, 4, 6, 8, 1])
print(x.intersect(y, z))
print(x.union(y, z))
入出力結果(Terminal)
$ ./sample.py Set: [1, 5] Set: [1, 3, 5, 7, 2, 4, 6] Set: ['p', 'y', 't', 'h', 'o', 'n'] y p y t h o n 共通部分 Set: ['p', 'o', 'n'] 和集合 Set: ['p', 'y', 't', 'h', 'o', 'n', 'r', 'g', 'a', 'm', 'i'] Set: [1] Set: [1, 3, 5, 7, 2, 4, 6, 8] $
0 コメント:
コメントを投稿