数を扱う

基本数学演習

[1]:
import unittest


class TestArithmeticOperations(unittest.TestCase):
    def test_addtion(self):
        self.assertEqual(1 + 2, 3)
        self.assertEqual(1 + 3.5, 4.5)
        self.assertEqual(-1 + 2.5, 1.5)
        self.assertEqual(-1.1 + 5, 3.9)

    def test_subtract(self):
        self.assertEqual(100 - 45, 55)

    def test_multipliction(self):
        self.assertEqual(3 * 2, 6)
        self.assertEqual(3.5 * 1.5, 5.25)
        self.assertEqual(2 ** 2, 4)
        self.assertEqual(2 ** 10, 1024)
        self.assertEqual(1 ** 10, 1)
        self.assertEqual(8 ** (1 / 3), 2.0)

    def test_division(self):
        self.assertEqual(3 / 2, 1.5)
        self.assertEqual(4 / 2, 2)
        self.assertEqual(3 // 2, 1)
        self.assertEqual(-3 // 2, -2)
        self.assertEqual(9 % 2, 1)

    def test_muliti_operation(self):
        self.assertEqual(5 + 5 * 5, 30)
        self.assertEqual((5 + 5) * 5, 50)


if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)

.....
----------------------------------------------------------------------
Ran 5 tests in 0.003s

OK

ラベル:名前に数を割り当てる

[2]:
import unittest


class TestLabelOperations(unittest.TestCase):
    def test_addition(self):
        a = 3
        self.assertEqual(a + 1, 4)
        a = 5
        self.assertEqual(a + 1, 6)


if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)

......
----------------------------------------------------------------------
Ran 6 tests in 0.004s

OK

様々な種類の数

[3]:
import unittest


class TestNumberType(unittest.TestCase):
    def test_int(self):
        assert type(3) is int
        assert type(int(3.8)) is int
        assert type(int(3.0)) is int

    def test_float(self):
        assert type(3.5) is float
        assert type(3.0) is float
        assert type(float(3)) is float


if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)

........
----------------------------------------------------------------------
Ran 8 tests in 0.006s

OK

分数を扱う

[4]:
import unittest
from fractions import Fraction


class TestFraction(unittest.TestCase):
    def test_01(self):
        f = Fraction(3, 4)
        self.assertEqual(f, 3 / 4)

    def test_02(self):
        f = Fraction(3, 4) + 1 + 1.5
        self.assertEqual(f, 3.25)

    def test_03(self):
        f = Fraction(3, 4) + 1 + Fraction(1 / 4)
        self.assertEqual(f, 2 / 1)


if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)

...........
----------------------------------------------------------------------
Ran 11 tests in 0.007s

OK

複素数

[5]:
import unittest


class TestComplexNumber(unittest.TestCase):
    def test_01(self):
        a = 2 + 3j
        assert type(a) is complex

    def test_02(self):
        a = complex(2, 3)
        self.assertEqual(a, 2+3j)

    def test_03(self):
        a = complex(2, 3)
        b = 3 + 3j
        self.assertEqual(a + b, 5+6j)

    def test_04(self):
        a = complex(2, 3)
        b = 3 + 3j
        self.assertEqual(a * b, -3+15j)
        self.assertEqual(a/b, 0.8333333333333334+0.16666666666666666j)

    def test_05(self):
        z = 2 + 3j
        self.assertEqual(z.real, 2.0)
        self.assertEqual(z.imag, 3.0)
        self.assertEqual(z.conjugate(), 2-3j)
        self.assertEqual((z.real ** 2 + z.imag ** 2)**0.5, 3.605551275463989)
        self.assertEqual(abs(z), 3.605551275463989)


if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)
................
----------------------------------------------------------------------
Ran 16 tests in 0.010s

OK

例外と不当入力の処理

[6]:
import unittest


def exception(number):
    try:
        a = float(number)
        print(a)
    except ValueError:
        print('An invalid number')
        raise ValueError


class TestException(unittest.TestCase):
    def test_01(self):
        with self.assertRaises(ValueError):
            exception('Hoge')

    def test_02(self):
        self.assertFalse(1.1.is_integer())
        self.assertTrue(1.0.is_integer())


if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)

..................
An invalid number

----------------------------------------------------------------------
Ran 18 tests in 0.013s

OK

分数と複素数を入力

[7]:
import unittest
from fractions import Fraction


def exception2(number):
    try:
        a = Fraction(number)
        print(a)
    except ZeroDivisionError:
        print('An invalid number')
        raise ZeroDivisionError


def exception3(number):
    try:
        a = complex(number)
        print(a)
    except ZeroDivisionError:
        print('An invalid number')
        raise ZeroDivisionError


class TestException(unittest.TestCase):
    def test_01(self):
        with self.assertRaises(ZeroDivisionError):
            exception2(3/0)

    def test_02(self):
        with self.assertRaises(ValueError):
            exception3('2 + 3j')


if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)

..................
----------------------------------------------------------------------
Ran 18 tests in 0.011s

OK

数学を行うプログラムを書く

整数の因数を計算する

[8]:
import unittest


'''
0を除く整数aが別の整数bの因数か調べる
'''
def is_factor(a, b):
    if b % a == 0:
        return True
    else:
        return False


'''
整数の因数を見つける
'''
def factors(b):
    arr = []

    for i in range(1, b + 1):
        if b % i == 0:
            print(i)
            arr.append(i)

    return arr


class TestFactor(unittest.TestCase):
    def test_01(self):
        self.assertTrue(is_factor(4, 1024))

    def test_02(self):
        self.assertEqual(factors(25),[1,5,25])


if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)

....................
1
5
25

----------------------------------------------------------------------
Ran 20 tests in 0.013s

OK

乗算表を生成する

[9]:
import unittest

'''
乗算表生成器
'''
def multi_table(a):
    arr = []
    for i in range(1, 11):
        msg = '{0} x {1} = {2}'.format(a, i, a * i)
        print(msg)
        arr.append(msg)

    return arr

class TestMultiTable(unittest.TestCase):
    def test_01(self):
        expect = ['5 x 1 = 5',
                  '5 x 2 = 10',
                  '5 x 3 = 15',
                  '5 x 4 = 20',
                  '5 x 5 = 25',
                  '5 x 6 = 30',
                  '5 x 7 = 35',
                  '5 x 8 = 40',
                  '5 x 9 = 45',
                  '5 x 10 = 50']
        self.assertEqual(multi_table(5), expect)


if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)

.....................
1
5
25
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

----------------------------------------------------------------------
Ran 21 tests in 0.017s

OK

測定単位を変換する

[10]:
import unittest

'''
単位換算プログラム
'''
def km_miles(arg):
    km = float(arg)
    miles = km / 1.609
    msg = 'Distance in miles: {0}'.format(miles)
    print(msg)
    return miles


def miles_km(arg):
    miles = float(arg)
    km = miles * 1.609
    msg = 'Distance in kilometers: {0}'.format(km)
    print(msg)
    return km


class TestUnitConverter(unittest.TestCase):
    def test_01(self):
        self.assertEqual(km_miles(160.9), 100)

    def test_02(selfs):
        selfs.assertEqual(miles_km(100), 160.9)


if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)

.......................
1
5
25
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
Distance in miles: 100.0
Distance in kilometers: 160.9

----------------------------------------------------------------------
Ran 23 tests in 0.014s

OK

2次方程式の解を求める

\(x_1 = {-b + \sqrt{b^2-fac} \over 2a}\)

\(x_2 = {-b - \sqrt{b^2-fac} \over 2a}\)

[11]:

import unittest


'''
2次方程式求解電卓
'''
def roots(a, b, c):
    arr = []
    D = (b*b - 4*a*c)**0.5
    x_1 = (-b + D)/(2*a)
    x_2 = (-b - D)/(2*a)
    print('x1: {0}'.format(x_1))
    print('x2: {0}'.format(x_2))
    return x_1,x_2


class TestRoots(unittest.TestCase):
    def test_01(self):
        self.assertEqual(roots(1,2,1),(-1.0,-1.0))

    def test_02(self):
        self.assertEqual(roots(1,1,1),(-0.49999999999999994+0.8660254037844386j,-0.5-0.8660254037844386j))






if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)

.........................
1
5
25
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
x1: -1.0
x2: -1.0
x1: (-0.49999999999999994+0.8660254037844386j)
x2: (-0.5-0.8660254037844386j)
Distance in miles: 100.0
Distance in kilometers: 160.9

----------------------------------------------------------------------
Ran 25 tests in 0.014s

OK