2015年11月1日日曜日

開発環境

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

Doing Math with Python: Use Programming to Explore Algebra, Statistics, Calculus, and More! (Amit Saha (著)、No Starch Press)のChapter 1.(Working with Numbers)、Programming Challenges #4: Fraction Calculator(No. 793)を解いてみる。

#3: Fraction Calculator(No. 793)

コード(Emacs)

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

import fractions

def add(a, b):
    print('Result of Adition: {0}'.format(a + b))

def sub(a, b):
    print('Result of Subtraction: {0}'.format(a - b))

def mul(a, b):
    print('Result of Multiplication: {0}'.format(a * b))

def div(a, b):
    print('Result of Division: {0}'.format(a / b))

if __name__ == '__main__':
    while True:
        a = input('Enter first fraction: ')
        if a == 'q':
            break
        a = fractions.Fraction(a)
        b = fractions.Fraction(input('Enter second fraction: '))
        op = input('Operation to perform - Add, Subtract, Divide, Multiply: ')
        if op == 'Add':
            add(a, b)
        elif op == 'Subtract':
            sub(a, b)
        elif op == 'Divide':
            div(a, b)
        elif op == 'Multiply':
            mul(a, b)
        else:
            print("Unknown operation: '{0}'".format(op))

入出力結果(Terminal, IPython)

$ ./sample4.py
Enter first fraction: 3/4
Enter second fraction: 1/4
Operation to perform - Add, Subtract, Divide, Multiply: Add
Result of Adition: 1
Enter first fraction: 3/4
Enter second fraction: 1/4
Operation to perform - Add, Subtract, Divide, Multiply: Subtract
Result of Subtraction: 1/2
Enter first fraction: 3/4
Enter second fraction: 1/4
Operation to perform - Add, Subtract, Divide, Multiply: Multiply
Result of Multiplication: 3/16
Enter first fraction: 3/4
Enter second fraction: 1/4
Operation to perform - Add, Subtract, Divide, Multiply: Divide
Result of Division: 3
Enter first fraction: 3/4
Enter second fraction: 1/4
Operation to perform - Add, Subtract, Divide, Multiply: A
Unknown operation: 'A'
Enter first fraction: q
$ 

0 コメント:

コメントを投稿