## 2018年11月6日火曜日

### Algorithm - Python - 帽子を全員で揃える(条件分岐、if/else、入れ子)

コード(Emacs)

Python 3

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

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

start = 0
forward = 0
backward = 0
intervals = []
for i in range(1, len(caps)):
if caps[start] != caps[i]:
intervals.append((start, i - 1, caps[start]))
if caps[start] == 'F':
forward += 1
else:
backward += 1
start = i
intervals.append((start, len(caps) - 1, caps[start]))
if caps[start] == 'F':
forward += 1
else:
backward += 1
if forward < backward:
flip = 'F'
else:
flip = 'B'

# 修正箇所
for t in intervals:
if t[2] == flip:
if t[0] == t[1]:
print(f'Person at position {t[0]} flip your cap!')
else:
print(
f'People in positions {t[0]} through {t[1]} flip your caps!'
)

for cap in [caps1, caps2]:
print()
```

```\$ ./sample1.py
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!

People in positions 2 through 4 flip your caps!
People in positions 6 through 8 flip your caps!

\$
```