開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの無料機能制限版、light版)
- Script言語: Python
『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のVI部(クラスとオブジェクト指向プログラミング)のまとめ演習5(Setクラス)を解いてみる。
その他参考書籍
5.
コード(TextWrangler)
sample.py
#!/usr/bin/env python
#-*- 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 __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: " + repr(self.data)
入出力結果(Terminal)
$ python
Python 3.2.3 (default, Apr 18 2012, 20:17:30)
[GCC 4.2.1 Compatible Apple Clang 3.0 (tags/Apple/clang-211.12)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from sample import Set
>>> a=Set([1,2,3,4,5])
>>> b=Set([5,6,7,8,9,0,1])
>>> a & b
Set: [1, 5]
>>> a | b
Set: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> chars = Set("kamimura")
>>> chars[1]
'a'
>>> chars.__getitem__(1)
'a'
>> for x in chars:
... print(x)
...
k
a
m
i
u
r
>>> chars
Set: ['k', 'a', 'm', 'i', 'u', 'r']
>>> str = "ka python"
>> chars & str
Set: ['k', 'a']
>>> chars | str
Set: ['k', 'a', 'm', 'i', 'u', 'r', ' ', 'p', 'y', 't', 'h', 'o', 'n']
>>> quit()
$
Setのサブクラスを作成
コード(TextWrangler)
sample.py
#!/usr/bin/env python
#-*- 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 __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: " + repr(self.data)
class Sub(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.data[:]
for other in others:
for x in other:
if not x in res:
res.append(x)
return Set(res)
if __name__ == '__main__':
a = Sub([1,2,3,4,5])
b = Sub([5,6,7,8,9,0])
c = Sub([0,1,2,3])
print(a.intersect(b,c))
print(a.union(b,c))
print(a.intersect([1,2],[2,3,4]))
print(a.union([1,2],[9,10,11,12]))
入出力結果(Terminal)
$ ./sample.py Set: [] Set: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] Set: [2] Set: [1, 2, 3, 4, 5, 9, 10, 11, 12] $
0 コメント:
コメントを投稿