## 2020年1月8日水曜日

### Python - Repeating Code Using Loops - remove the negative numbers from the list, del, while loop, if statement

Practical Programming: An Introduction to Computer Science Using Python 3.6 (Paul Gries(著)、Jennifer Campbell(著)、Jason Montojo(著)、Pragmatic Bookshelf)のChapter 9(Repeating Code Using Loops)、Exercise 12の解答を求めてみる。

コード

```#!/usr/bin/env python3
import doctest
from typing import List

print('12.')

def remove_neg(num_list: List[float]) -> None:
"""
>>> numbers = [-5, 1, -3, 2]
>>> remove_neg(numbers)
>>> numbers
[1, 2]
>>> numbers = [1, 2, 3, -3, 6, -1, -3, 1]
>>> remove_neg(numbers)
>>> numbers
[1, 2, 3, 6, 1]
"""
i: int = 0
while i < len(num_list):
if num_list[i] < 0:
del num_list[i]
else:
i += 1

if __name__ == '__main__':
doctest.testmod()
```

```% ./sample12.py
12.
**********************************************************************
File "./sample12.py", line 16, in __main__.remove_neg
Failed example:
numbers
Expected:
[1, 2, 3, 6, 1]
Got:
[1, 2, 3, 6, -3, 1]
**********************************************************************
1 of   6 in __main__.remove_neg
***Test Failed*** 1 failures.
% ./sample12.py
12.
% ./sample12.py -v
12.
Trying:
numbers = [-5, 1, -3, 2]
Expecting nothing
ok
Trying:
remove_neg(numbers)
Expecting nothing
ok
Trying:
numbers
Expecting:
[1, 2]
ok
Trying:
numbers = [1, 2, 3, -3, 6, -1, -3, 1]
Expecting nothing
ok
Trying:
remove_neg(numbers)
Expecting nothing
ok
Trying:
numbers
Expecting:
[1, 2, 3, 6, 1]
ok