Created
September 11, 2020 15:22
-
-
Save rzrn/9fb9ecf0950d6dce61012e53e88c5eb4 to your computer and use it in GitHub Desktop.
Задача про мышь
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from random import randint | |
print("Введите число коробок: ", end='') | |
N = int(input()) | |
# Ставит мышь в случайное место | |
def initmouse(): | |
# Да-да, глобальная переменная, фу‐фу | |
global mouse | |
mouse = randint(1, N) | |
# Возвращает 1 или -1 случайным образом | |
def randdir(): | |
n = randint(0, 1) | |
return -1 if n == 0 else 1 | |
# Меняет позицию мыши на случайную, если это возможно | |
def runaway(): | |
global mouse | |
if mouse == 1: mouse = 2 | |
elif mouse == N: mouse = N - 1 | |
else: mouse += randdir() | |
# Производит выстрел в коробку n | |
# Возвращает True, если мышь была убита | |
def shoot(n): | |
if mouse == n: | |
return True | |
else: | |
runaway() | |
return False | |
# А вот тут пошёл сам алгоритм убийства мышки | |
def killthemouse(): | |
for i in range(2, N + 1): | |
if shoot(i): return True | |
for i in range(1 if N % 2 == 1 else 2, N + 1): | |
if shoot(i): return True | |
# Если алгоритм провалился | |
return False | |
# Теперь идут тесты | |
# Прогоняем алгоритм 1000 раз, а потом выводим win rate | |
total = 1000 | |
success = 0 | |
for i in range(0, total): | |
initmouse() | |
if killthemouse(): success += 1 | |
print("%d испытаний, из них %d успешных" % (total, success)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
А как у тебя получилось, что количество выстрелов зависит от четности или нечетности N? Сложна, я так и не понял.
Вот с таким алгоритмом (если ничего не напутал) получается (2*N-3) выстрела