计算机科学热身赛第二级挑战
天敌相遇吗
在野生动物园有Squirrel、Turtle、fox和Snake四种动物之间存在天敌或者朋友的关系,
它们每天观察其他三只动物,再决定是否走出自己的安全小窝。假如他们的行为如下。
Squirrel、fox都出来了,Snake才会出来!
Squirrel,Snake中的某一只出来,或Squirrel和Snake都出来的情况下,fox才会出来!
Squirrel看到Snake没有出来时,Squirrel才会出来
Turtle很佛系,Turtle不关心其他三只动物的状态,Turtle保持前一天的状态
假设第一天,四只动物都在窝里。预测若干天以后各自的状态是什么?
并且试着找到规律?
第一种写法是判断前后两天的状态,如果不同,按规则继续循环操作;前后两天状态相同则终止循环,返回结果
#Squirrel,Turtle,fox,Snake= 0,0,0,0
def repeat_motion(day,Squirrel,Turtle,fox,Snake):
d,same = 1,True
status = [(0,0,0,0)]
#Squirrel,Turtle,fox,Snake第一天初始状态status
while same:
d += 1
if Turtle == 1 and fox == 1:
snake = 1
if Squirrel == 1 or Snake == 1:
fox = 1
if Snake == 0:
Squirrel = 1
Turtle = Turtle
same = any(x!=y for x,y in list(zip((Squirrel,Turtle,fox,Snake),status[-1])))
#判断前后两天的状态是否相同
if same:
status.append([Squirrel,Turtle,fox,Snake])
else:return d,status[-1]
print(repeat_motion(day,Squirrel,Turtle,fox,Snake))
4, [1, 0, 1, 0]
第二种写法简洁的while循环
# day=1时,Squirrel,Turtle,fox,Snake都在窝里=False
Squirrel_1 = False
Turtle_1 = False
fox_1 = False
Snake_1 = False
day = 1
while True:
day += 1
Squirrel = not Snake_1
Snake = Turtle_1 and fox_1
fox = Squirrel_1 or Snake_1
Turtle = Turtle_1
print(day)
if (Squirrel,Turtle,fox,Snake)==(Squirrel_1,Turtle_1,fox_1,Snake_1):
break
Squirrel_1,Turtle_1,fox_1,Snake_1 = Squirrel,Turtle,fox,Snake
print(f'第{day}天后,动物都稳定在下述状态:')
print("Squirrel:", Squirrel)
print("Turtle:", Turtle)
print("fox:", fox)
print("Snake:", Snake)
第4天后,动物都稳定在下述状态:
Squirrel: True
Turtle: False
fox: True
Snake: False
两种写法的输出结果一致,在第四天时稳定持续下来:
松鼠没有待在窝里,一直在外;
乌龟一直待在窝里;
狐狸没有待在窝里,一直在外;
蛇一直待在窝里;
真实大自然并非如此,这是一种假设的情况。目的是练习运用编程解决确定规则前提下的任务。