開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Python 3.4 (プログラミング言語)
Head First C ―頭とからだで覚えるCの基本(David Griffiths (著)、Dawn Griffiths (著) 中田 秀基(監訳)(翻訳)、木下 哲也 (翻訳)、オライリージャパン)の7章(高度な関数: 関数を最大限に活用する)、長いエクササイズ(p.328)をpythonで考えてみる。
長いエクササイズ(p.328)
コード(BBEdit, Emacs)
sample328.py
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@property
def area(self):
return self.width * self.height
def __repr__(self):
return '{0}x{1}'.format(self.width, self.height)
nums = [5, 1, 4, 2, 3]
rectangles = [Rectangle(1, 5), Rectangle(1, 1), Rectangle(1, 4),
Rectangle(1, 2), Rectangle(1, 3)]
strs = ['Abc', 'Def']
print('sorted')
print(sorted(nums))
print(sorted(nums, reverse=True))
print(sorted(rectangles, key=lambda r:r.area))
print(sorted(rectangles, key=lambda r:r.area, reverse=True))
print(sorted(strs))
print(sorted(strs, reverse=True))
print('list.sort')
nums.sort()
print(nums)
nums.sort(reverse=True)
print(nums)
rectangles.sort(key=lambda r:r.area)
print(rectangles)
rectangles.sort(key=lambda r:r.area, reverse=True)
print(rectangles)
strs.sort()
print(strs)
strs.sort(reverse=True)
print(strs)
入出力結果(Terminal, IPython)
$ ./sample328.py sorted [1, 2, 3, 4, 5] [5, 4, 3, 2, 1] [1x1, 1x2, 1x3, 1x4, 1x5] [1x5, 1x4, 1x3, 1x2, 1x1] ['Abc', 'Def'] ['Def', 'Abc'] list.sort [1, 2, 3, 4, 5] [5, 4, 3, 2, 1] [1x1, 1x2, 1x3, 1x4, 1x5] [1x5, 1x4, 1x3, 1x2, 1x1] ['Abc', 'Def'] ['Def', 'Abc'] $
0 コメント:
コメントを投稿