開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc., Emacs(Text Editor)
- プログラミング言語: Python
初めてのコンピュータサイエンス(Jennifer Campbell、Paul Gries、Jason Montojo、Greg Wilson(著)長尾 高弘(翻訳))の9章(集合と辞書)の9.5(練習問題)を解いてみる。
1.
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
def find_dups(l):
s = set()
for x in l:
if l.count(x) >= 2:
s.add(x)
return s
for x in [[],[1,2,3,4,5], [1,2,3,4,5,1,2],[1,2,3,4,5,1,2,1]]:
print(x, find_dups(x))
入出力結果(Terminal)
$ ./sample.py
[] set()
[1, 2, 3, 4, 5] set()
[1, 2, 3, 4, 5, 1, 2] {1, 2}
[1, 2, 3, 4, 5, 1, 2, 1] {1, 2}
$
2.
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
def mating_pairs(males, females):
pairs = set()
while males:
pairs.add((males.pop(), females.pop()))
return pairs
print(mating_pairs({'a','b',1,2}, {'c',3,'d',4}))
入出力結果(Terminal)
$ ./sample.py
{(1, 'd'), ('b', 4), (2, 3), ('a', 'c')}
$
3.
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
def getAuthors(filename):
authors = set()
with open(filename) as f:
for line in f:
if line[0:6] == "AUTHOR":
line = line[6:].strip()
if line != "":
authors.add(line)
return authors
import sys
for filename in sys.argv[1:]:
print(getAuthors(filename))
入出力結果(Terminal)
$ ./sample.py tmp1.txt tmp2.txt
set()
{'kamimura', '長尾高弘'}
$
5.
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
def count_values(d):
res = []
for k, v in d.items():
if not v in res:
res.append(v)
return len(res)
print(count_values({'赤':1,'緑':1,'青':2}))
入出力結果(Terminal)
$ ./sample.py 2 $
6.
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
def find_least(d):
m = 1
for k, v in d.items():
if v < m:
res = k
return res
if __name__ == '__main__':
d = {'ニュートロン':0.55, '陽子':0.21,
'中間子':0.03, 'ミューオン':0.07,
'ニュートリノ':0.14}
print(find_least(d))
入出力結果(Terminal)
$ ./sample.py 中間子 $
7.
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
def count_duplicates(d):
duplicates = []
res = 0
for v in d.values():
if v in duplicates:
res += 1
else:
duplicates.append(v)
return res
if __name__ == '__main__':
d1 = {'a':1,'b':1,'c':2,'d':3,'e':2}
d2 = {'a':1,'b':2,'c':3,'d':4,'e':5}
for d in [d1, d2]:
print(d, count_duplicates(d))
入出力結果(Terminal)
$ ./sample.py
{'e': 2, 'd': 3, 'a': 1, 'c': 2, 'b': 1} 2
{'e': 2, 'd': 3, 'a': 1, 'c': 2, 'b': 1} 0
$
8.
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
def fetch_and_set(d, key, new_value):
if key in d:
res = d[key]
d[key] = new_value
return res
raise KeyError("Unable to replace value for nonexistent key")
if __name__ == '__main__':
d1 = {'a':1,'b':2,'c':3,'d':4,'e':5}
d2 = {'a':1,'b':2}
for d in [d1, d2]:
try:
res = fetch_and_set(d, 'd', "new value")
print("元の値: {0} 新たな辞書: {1}".format(res, d))
except Exception as err:
print(type(err), err, err.args)
入出力結果(Terminal)
$ ./sample.py
元の値: 4 新たな辞書: {'e': 5, 'd': 'new value', 'c': 3, 'b': 2, 'a': 1}
<class 'KeyError'> 'Unable to replace value for nonexistent key' ('Unable to replace value for nonexistent key',)
$
9.
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
def is_balanced(rgb):
return rgb['R'] + rgb['G'] + rgb['B'] == 1
if __name__ == '__main__':
for d in [{'R':0.2, 'G':0.3,'B':0.5}, {'R':0.2, 'G':0.3,'B':0.4}]:
print(d, is_balanced(d))
入出力結果(Terminal)
$ ./sample.py
{'R': 0.2, 'B': 0.5, 'G': 0.3} True
{'R': 0.2, 'B': 0.4, 'G': 0.3} False
$
10.
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
def dict_itersect(x, y):
res = {}
for k in x.keys():
if (k in y) and x[k] == y[k]:
res[k] = x[k]
return res
if __name__ == '__main__':
d1 = {'a':1,'b':2,'c':3,'d':4,'e':5}
d2 = {'f':6,'g':7,'a':1,'h':8,'b':2}
print(d1, d2, dict_itersect(d1, d2), sep="\n")
入出力結果(Terminal)
$ ./sample.py
{'e': 5, 'd': 4, 'a': 1, 'c': 3, 'b': 2}
{'g': 7, 'f': 6, 'a': 1, 'h': 8, 'b': 2}
{'a': 1, 'b': 2}
$
11.
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
def db_headings(d):
res = set()
for v in d.values():
res = res.union(set(v.keys()))
return res
if __name__ == '__main__':
d = {
'Jグードル': {
'姓':'グドール',
'名':'ジェーン',
'生年':1934,
'没年':None,
'注目':'霊長類研究者',
'著作':['In the Shadow of Man', 'The Chimpanzees of Gombe']
},
'Rフランクリン': {
'姓':'フランクリン',
'名':'ロザリンド',
'生年':1920,
'没年':1957,
'注目':'DNAの発見に貢献'
},
'Rカーソン': {
'姓':'カーソン',
'名':'レイチェル',
'生年':1907,
'没年':1964,
'注目':'DDTの害毒に注意を喚起',
'著作':['沈黙の春']
}
}
print(db_headings(d))
入出力結果(Terminal)
$ ./sample.py
{'名', '著作', '注目', '姓', '生年', '没年'}
$
12.
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
def db_consistent(d):
keys = set()
for v in d.values():
keys = set(v.keys())
break
for v in d.values():
if keys != set(v.keys()):
return False
return True
if __name__ == '__main__':
d1 = {
'Jグードル': {
'姓':'グドール',
'名':'ジェーン',
'生年':1934,
'没年':None,
'注目':'霊長類研究者',
'著作':['In the Shadow of Man', 'The Chimpanzees of Gombe']
},
'Rフランクリン': {
'姓':'フランクリン',
'名':'ロザリンド',
'生年':1920,
'没年':1957,
'注目':'DNAの発見に貢献'
},
'Rカーソン': {
'姓':'カーソン',
'名':'レイチェル',
'生年':1907,
'没年':1964,
'注目':'DDTの害毒に注意を喚起',
'著作':['沈黙の春']
}
}
d2 = {
'Jグードル': {
'姓':'グドール',
'名':'ジェーン',
'生年':1934,
'没年':None,
'注目':'霊長類研究者',
'著作':['In the Shadow of Man', 'The Chimpanzees of Gombe']
},
'Rフランクリン': {
'姓':'フランクリン',
'名':'ロザリンド',
'生年':1920,
'没年':1957,
'注目':'DNAの発見に貢献',
"著作": None
},
'Rカーソン': {
'姓':'カーソン',
'名':'レイチェル',
'生年':1907,
'没年':1964,
'注目':'DDTの害毒に注意を喚起',
'著作':['沈黙の春']
}
}
for d in [d1, d2]:
print(db_consistent(d))
入出力結果(Terminal)
$ ./sample.py False True $
13.
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
def counter(filename):
count = {}
with open(filename) as f:
for line in f:
line = line.strip()
if not line:
continue
count[line] = count.get(line, 0) + 1
return count
def k_vTov_k(d):
freq = {}
for k, v in d.items():
if v in freq:
freq[v].append(k)
else:
freq[v] = [k]
return freq
if __name__ == '__main__':
import sys
print(k_vTov_k(counter(sys.argv[1])))
入出力結果(Terminal)
$ cat tmp.txt
a
ab
abc
abcd
abcde
a
ab
abc
abcd
a
ab
abc
a
ab
a
a
$ ./sample.py tmp.txt
{1: ['abcde'], 2: ['abcd'], 3: ['abc'], 4: ['ab'], 6: ['a']}
$
14.
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
def sparse_add(x, y):
res = x.copy()
for k, v in y.items():
if k in res:
res[k] += v
else:
res[k] = v
return res
def sparse_dot(x, y):
res = 0
for k in x:
if k in y:
res += x[k] * y[k]
return res
if __name__ == '__main__':
d1 = {0:1, 5:2, 6:3,10:4}
d2 = {1:5, 20:6, 5:7, 6:8}
print(d1, d2)
for func in [sparse_add, sparse_dot]:
print(func.__name__, func(d1, d2))
入出力結果(Terminal)
$ ./sample.py
{0: 1, 10: 4, 5: 2, 6: 3} {1: 5, 20: 6, 5: 7, 6: 8}
sparse_add {0: 1, 1: 5, 20: 6, 5: 9, 6: 11, 10: 4}
sparse_dot 38
$
0 コメント:
コメントを投稿