## 2018年11月21日水曜日

### Algorithm - Python - 水晶をどうぞ壊してください(壊れた水晶の個数、カウンター、forループ、if文、break文)

コード(Emacs)

Python 3

```#!/usr/bin/env python3
def convert_to_decimal(r, d, rep):
'''
>>> convert_to_decimal(4, 4, [0, 0, 0, 0])
0
>>> convert_to_decimal(4, 4, [1, 2, 3, 3])
111
>>> convert_to_decimal(4, 4, [2, 0, 0, 0])
128
>>> convert_to_decimal(4, 5, [1, 0, 0, 1, 4]) # 誤植？
65
>>> convert_to_decimal(4, 5, [1, 3, 3, 3, 4]) # 誤植？
127
>>> convert_to_decimal(4, 4, [1, 0, 0, 1]) # 修正
65
>>> convert_to_decimal(4, 4, [1, 3, 3, 3]) # 修正
127
>>> convert_to_decimal(4, 4, [1, 2, 0, 1])
97
>>> convert_to_decimal(4, 4, [1, 2, 3, 3])
111
'''
return sum([rep[i] * r ** (d - (i + 1)) for i in range(d)])

def how_hard_is_the_crystal(n, d, did_break=None):
r = 1
while r ** d <= n:
r += 1

# while r ** (d - 1) > n:
#     d -= 1
ball_number = 1
num_drops = 0
floor_no_break = [0] * d
for i in range(d):
for j in range(r - 1):
floor_no_break[i] += 1
floor = convert_to_decimal(r, d, floor_no_break)
if floor > n:
floor_no_break[i] -= 1
break
print(f'Broken balls: {ball_number - 1}')
print(f'Drop ball {ball_number} from floor {floor}')
# did_break = input('Did the ball break (yes/no)?: ')
num_drops += 1
# if did_break == 'yes':
if did_break[i] == 'yes':
floor_no_break[i] -= 1
ball_number += 1
break
hardness = convert_to_decimal(r, d, floor_no_break)
return hardness, num_drops

if __name__ == '__main__':
# import doctest
# doctest.testmod()

def yes_no(n):
if n % 2 == 0:
return 'yes'
return 'no'
for did_break in [['no'] * 6,
['yes'] * 6,
[yes_no(i) for i in range(6)],
[yes_no(i + 1) for i in range(6)]]:
print(how_hard_is_the_crystal(128, 6, did_break))
```

```\$ ./sample2.py
Broken balls: 0
Drop ball 1 from floor 81
Broken balls: 0
Drop ball 1 from floor 108
Broken balls: 0
Drop ball 1 from floor 117
Broken balls: 0
Drop ball 1 from floor 126
Broken balls: 0
Drop ball 1 from floor 127
Broken balls: 0
Drop ball 1 from floor 128
(128, 6)
Broken balls: 0
Drop ball 1 from floor 81
Broken balls: 1
Drop ball 2 from floor 27
Broken balls: 2
Drop ball 3 from floor 9
Broken balls: 3
Drop ball 4 from floor 3
Broken balls: 4
Drop ball 5 from floor 1
(0, 5)
Broken balls: 0
Drop ball 1 from floor 81
Broken balls: 0
Drop ball 1 from floor 108
Broken balls: 1
Drop ball 2 from floor 90
Broken balls: 1
Drop ball 2 from floor 99
Broken balls: 1
Drop ball 2 from floor 102
Broken balls: 2
Drop ball 3 from floor 100
Broken balls: 2
Drop ball 3 from floor 101
(101, 7)
Broken balls: 0
Drop ball 1 from floor 81
Broken balls: 1
Drop ball 2 from floor 27
Broken balls: 1
Drop ball 2 from floor 54
Broken balls: 1
Drop ball 2 from floor 63
Broken balls: 2
Drop ball 3 from floor 57
Broken balls: 2
Drop ball 3 from floor 60
Broken balls: 2
Drop ball 3 from floor 61
(60, 7)
\$
```