## 2018年11月7日水曜日

### Algorithm - Python - 帽子を全員で揃える(最適化、1パスアルゴリズム、for loop(for/in))

コード(Emacs)

Python 3

```#!/usr/bin/env python3

caps1 = ['F', 'F', 'B', 'B', 'B', 'F', 'B', 'B', 'B', 'F', 'F', 'B', 'F']
caps2 = ['F', 'B', 'F', 'B', 'B', 'B', 'F', 'B', 'F', 'B', 'B', 'F', 'F']
case3 = []
case4 = ['F']

def please_conform_one_pass(caps):
if 0 <= len(caps) <= 1:
return
caps = caps + [caps[0]]
start_i = 0
for i in range(1, len(caps)):
if caps[i] != caps[i - 1]:
if caps[i] != caps[0]:
start_i = i
elif start_i == i - 1:
print(f'Person at position {i - 1} flip your cap!')
else:
print(f'People in positions {start_i}'
f' through {i - 1} flip your caps!')

for caps in [caps1, caps2, case3, case4]:
print(caps)
please_conform_one_pass(caps)
print()
```

```\$ ./sample2.py
['F', 'F', 'B', 'B', 'B', 'F', 'B', 'B', 'B', 'F', 'F', 'B', 'F']
People in positions 2 through 4 flip your caps!
People in positions 6 through 8 flip your caps!
Person at position 11 flip your cap!

['F', 'B', 'F', 'B', 'B', 'B', 'F', 'B', 'F', 'B', 'B', 'F', 'F']
Person at position 1 flip your cap!
People in positions 3 through 5 flip your caps!
Person at position 7 flip your cap!
People in positions 9 through 10 flip your caps!

[]

['F']

\$
```