## 2020年5月18日月曜日

### Python - Searching and Sorting - bubble sort, beginning of the list

Practical Programming: An Introduction to Computer Science Using Python 3.6 (Paul Gries(著)、Jennifer Campbell(著)、Jason Montojo(著)、Pragmatic Bookshelf)のChapter 13(Searching and Sorting)、Exercise 6の解答を求めてみる。

コード

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

print('6.')

class TestBubbleSort2(TestCase):
def test_empty(self):
l = []
bubble_sort2(l)
self.assertEqual(l, [])

def test_one(self):
l = [1]
bubble_sort2(l)
self.assertEqual(l, [1])

def test_descent(self):
l = [2, 1]
bubble_sort2(l)
self.assertEqual(l, [1, 2])

def test_ascent(self):
l = [1, 2]
bubble_sort2(l)
self.assertEqual(l, [1, 2])

def test_duplicate(self):
l = [3, 3, 3]
bubble_sort2(l)
self.assertEqual(l, [3, 3, 3])

def test_general(self):
l = [3, 4, 7, -1, 2, 5]
bubble_sort2(l)
self.assertEqual(l, [-1, 2, 3, 4, 5, 7])

def test_general_duplicate(self):
l = [-5, 3, 0, 3, -6, 2, 1, 1]
bubble_sort2(l)
self.assertEqual(l, [-6, -5, 0, 1, 1, 2, 3, 3])

def bubble_sort2(l: list) -> None:
for i, _ in enumerate(l[:-1]):
for i in range(len(l) - 1, 0, -1):
if l[i] < l[i - 1]:
l[i], l[i - 1] = l[i - 1], l[i]

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

```% ./sample6.py -v
6.
test_ascent (__main__.TestBubbleSort2) ... ok
test_descent (__main__.TestBubbleSort2) ... ok
test_duplicate (__main__.TestBubbleSort2) ... ok
test_empty (__main__.TestBubbleSort2) ... ok
test_general (__main__.TestBubbleSort2) ... ok
test_general_duplicate (__main__.TestBubbleSort2) ... ok
test_one (__main__.TestBubbleSort2) ... ok

----------------------------------------------------------------------
Ran 7 tests in 0.000s

OK
%
```