2016年3月19日土曜日

開発環境

  • OS X El Capitan - Apple (OS)
  • Emacs (Text Editor)
  • Python 3.5 (プログラミング言語)

Think Python (Allen B. Downey (著)、 O'Reilly Media)のChapter 3.(Functions)のExercises 3-1、2、3(No. 784)を取り組んでみる。

Exercises 3-1、2、3(No. 784)

コード(Emacs)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
''' 3. Functions '''

def right_justify(s):
    print(s + ' ' * (70 - len(s)) + '#')

def do_twice(f, arg):
    f(arg)
    f(arg)

def print_twice(bruce):
    print(bruce)
    print(bruce)

def do_four(f, arg):
    do_twice(f, arg)
    do_twice(f, arg)    

def p(s):
    print(s, end='')

def print_horizontal_2(arg):
    do_twice(p, '+ - - - - ')
    print('+')

def print_vertical_2(arg):
    do_twice(p, '|         ')
    print('|')

def print_row2(arg):
    print_horizontal_2(None)
    do_four(print_vertical_2, None)

def print_grid2():
    do_twice(print_row2, None)
    print_horizontal_2(None)

def print_horizontal_4(arg):
    do_four(p, '+ - - - - ')
    print('+')

def print_vertical_4(arg):
    do_four(p, '|         ')
    print('|')

def print_row4(arg):
    print_horizontal_4(None)
    do_four(print_vertical_4, None)

def print_grid4():
    do_four(print_row4, None)
    print_horizontal_4(None)
    
if __name__ == '__main__':
    print('1.')
    right_justify('monty')

    print('2.')
    do_twice(print_twice, 'spam')
    do_four(print_twice, 'egg')

    print('3.')
    print_grid2()
    print_grid4()

入出力結果(Terminal, IPython)

$ ./sample1.py 
1.
monty                                                                 #
2.
spam
spam
spam
spam
egg
egg
egg
egg
egg
egg
egg
egg
3.
+ - - - - + - - - - +
|         |         |
|         |         |
|         |         |
|         |         |
+ - - - - + - - - - +
|         |         |
|         |         |
|         |         |
|         |         |
+ - - - - + - - - - +
+ - - - - + - - - - + - - - - + - - - - +
|         |         |         |         |
|         |         |         |         |
|         |         |         |         |
|         |         |         |         |
+ - - - - + - - - - + - - - - + - - - - +
|         |         |         |         |
|         |         |         |         |
|         |         |         |         |
|         |         |         |         |
+ - - - - + - - - - + - - - - + - - - - +
|         |         |         |         |
|         |         |         |         |
|         |         |         |         |
|         |         |         |         |
+ - - - - + - - - - + - - - - + - - - - +
|         |         |         |         |
|         |         |         |         |
|         |         |         |         |
|         |         |         |         |
+ - - - - + - - - - + - - - - + - - - - +
$

0 コメント:

コメントを投稿