2014年5月8日木曜日

開発環境

Learning Python (Mark Lutz (著)、Oreilly & Associates Inc)のPART Ⅵ.(Classes and OOP)、CHAPTER 32(Advanced Class Topics)、Test Your Knowledge: Part VI Exercises 5.(Set objects)を解いてみる。

その他参考書籍

5.(Set objects)

コード(BBEdit)

sample.py

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

from setwrapper import Set

# a.
s1 = Set([1,2,3,4,5])
s2 = Set([1,3,5,7,9,11])

print(s1 & s2)
print(s1 | s2)

# b. 呼び出されるメソッドは__getitem__
s = Set('python')
print(s[2])
print(s.__getitem__(2))

# c iterメソッドが呼び出される
for x in s:
    print(x)

# d.
print(s.intersect('scheme'))
print(s.union('scheme'))

# e.
class SubSet(Set):
    def intersect(self, *others):
        res = []
        for x in self:
            for other in others:
                if not x in other:
                    break
                res.append(x)
        return Set(res)
    def union(*others):
        res = []
        for other in others:
            for x in other:
                if not x in res:
                    res.append(x)
        return Set(res)

s1 = SubSet([1, 2, 3, 4, 5])
s2 = SubSet([2, 4])
s3 = SubSet([1, 3, 5])

print(s1.intersect(s2, s3))
print(s1.union(s2, s3))
print(s1.intersect(s2) & s2.intersect(s3))
print(s1.union(s2) | s2.union(s3))

# f.
class SubSet1(Set):
    def __getattr__(self, name):
        return getattr(self.data, name)
    def __add__(self, other):
        if isinstance(other, Set):
            other = other.data
        return Set(self.data + other)

s1 = SubSet1('python')
s2 = SubSet1('scheme')
print(s1.pop())
print(s1 + s2)

入出力結果(Terminal)

$ ./sample.py
Set:[1, 3, 5]
Set:[1, 2, 3, 4, 5, 7, 9, 11]
t
t
p
y
t
h
o
n
Set:['h']
Set:['p', 'y', 't', 'h', 'o', 'n', 's', 'c', 'e', 'm']
Set:[2, 4]
Set:[1, 2, 3, 4, 5]
Set:[]
Set:[1, 2, 3, 4, 5]
n
Set:['p', 'y', 't', 'h', 'o', 's', 'c', 'e', 'm']
$

0 コメント:

コメントを投稿