2014年7月18日金曜日

開発環境

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 __str__(self):
        return '{0}x{1}'.format(self.width, self.height)

def p(items):
    for item in items:
        print(item, end=' ')
    print()

scores = [543, 323, 32, 554, 11, 3, 112]
recs = [Rectangle(1, 5), Rectangle(1, 1), Rectangle(1, 4), Rectangle(1, 2),
        Rectangle(1, 3)]
names = ["abcd", "Dabc", "bcda", "Cdab", "Bcda", "Abcd", "cdab", "dabc"]

p(scores)
p(recs)
p(names)

print('昇順')
p(sorted(scores))
p(sorted(recs, key=lambda r: r.area))
p(sorted(names))

print()
p(scores)
p(recs)
p(names)

print('降順')
p(sorted(scores, key=lambda x: -x))
p(sorted(recs, key=lambda r: -r.area))

print()
p(scores)
p(recs)
p(names)

print('降順')
p(sorted(scores, reverse=True))
p(sorted(recs, key=lambda r: r.area, reverse=True))
p(sorted(names, reverse=True))

入出力結果(Terminal, IPython)

$ ./sample328.py 
543 323 32 554 11 3 112 
1x5 1x1 1x4 1x2 1x3 
abcd Dabc bcda Cdab Bcda Abcd cdab dabc 
昇順
3 11 32 112 323 543 554 
1x1 1x2 1x3 1x4 1x5 
Abcd Bcda Cdab Dabc abcd bcda cdab dabc 

543 323 32 554 11 3 112 
1x5 1x1 1x4 1x2 1x3 
abcd Dabc bcda Cdab Bcda Abcd cdab dabc 
降順
554 543 323 112 32 11 3 
1x5 1x4 1x3 1x2 1x1 

543 323 32 554 11 3 112 
1x5 1x1 1x4 1x2 1x3 
abcd Dabc bcda Cdab Bcda Abcd cdab dabc 
降順
554 543 323 112 32 11 3 
1x5 1x4 1x3 1x2 1x1 
dabc cdab bcda abcd Dabc Cdab Bcda Abcd 
$

0 コメント:

コメントを投稿