2019年11月6日水曜日

Python - Storing Collections of Data Using Lists - remove method, index method, insert method, extend method, reverse method, sort method

Practical Programming: An Introduction to Computer Science Using Python 3.6 (Paul Gries(著)、Jennifer Campbell(著)、Jason Montojo(著)、Pragmatic Bookshelf)のChapter 8(Storing Collections of Data Using Lists)、Exercise 4の解答を求めてみる。

コード

```#!/usr/bin/env python3
from unittest import TestCase, main

ids = [4353, 2314, 2956, 3382, 9362, 3900]

class MyTestCase(TestCase):
def test_a(self):
ids.remove(3382)
self.assertListEqual(ids, [4353, 2314, 2956, 9362, 3900])

def test_b(self):
index = ids.index(9362)
self.assertEqual(index, 3)

def test_c(self):
ids.insert(ids.index(9362) + 1, 4499)
self.assertListEqual(ids, [4353, 2314, 2956, 9362, 4499, 3900])

def test_d(self):
ids.extend([5566, 1830])
self.assertListEqual(
ids, [4353, 2314, 2956, 9362, 4499, 3900, 5566, 1830])

def test_e(self):
ids.reverse()
self.assertEqual(ids, [1830, 5566, 3900, 4499, 9362, 2956, 2314, 4353])

def test_f(self):
ids.sort()
self.assertEqual(ids, [1830, 2314, 2956, 3900, 4353, 4499, 5566, 9362])

if __name__ == '__main__':
main()
```

```% ./sample4.py -v
test_a (__main__.MyTestCase) ... ok
test_b (__main__.MyTestCase) ... ok
test_c (__main__.MyTestCase) ... ok
test_d (__main__.MyTestCase) ... ok
test_e (__main__.MyTestCase) ... ok
test_f (__main__.MyTestCase) ... ok

----------------------------------------------------------------------
Ran 6 tests in 0.000s

OK
%
```