2012年5月3日木曜日

開発環境

『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のVI部(クラスとオブジェクト指向プログラミング)のまとめ演習5(Setクラス)を解いてみる。

5.

コード(TextWrangler)

#!/usr/bin/env python
#encoding: 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 repr(self.data)
 def __add__(self,other): return self.union(other)

class SubSet(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(*args):
  res = []
  for arg in args:
   for x in arg:
    if not x in res:
     res.append(x)
  return Set(res)

if __name__ == '__main__':
 a = Set([1,2,3,4,5])
 b = Set([4,5,6,7,8,9,10])
 print('a:',a,'b:',b)
 print('a & b:',a & b)
 print('a | b:', a | b)
 strs = Set(['a','b','c','d','e'])
 print('strs:',strs)
 print('index 1:',strs[1])
 print('strs.__getitem__(1)',strs.__getitem__(1))
 for s in strs:
  print(s)
 str = 'defghij'
 print('str:',str)
 print('strs & str:',strs & str, 'strs | str:',strs | str)
 c = SubSet(['a','b','c','d','e'])
 d = SubSet(['c','d','e','f'])
 e = SubSet(['e','f','a','b'])
 print('c:',c,'d:',d,'e:',e)
 print('c & d & e:',c.intersect(d,e), 'c | d | e:',c.union(d,e))
 print('a+b:',a+b)

入出力結果(Terminal)

$ python sample.py
a: [1, 2, 3, 4, 5] b: [4, 5, 6, 7, 8, 9, 10]
a & b: [4, 5]
a | b: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
strs: ['a', 'b', 'c', 'd', 'e']
index 1: b
strs.__getitem__(1) b
a
b
c
d
e
str: defghij
strs & str: ['d', 'e'] strs | str: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
c: ['a', 'b', 'c', 'd', 'e'] d: ['c', 'd', 'e', 'f'] e: ['e', 'f', 'a', 'b']
c & d & e: ['e'] c | d | e: ['a', 'b', 'c', 'd', 'e', 'f']
a+b: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
$

こんな感じかな。。

0 コメント:

コメントを投稿