问题见图片
def how_likely_alive(size, startx, starty, n): sum_probability = 4 ** n # 所有可能的移动结果数 start_point = [(startx, starty)] # 定义起始位置坐标 while n > 0: end_point = [] # 定义空列表,存放移动后还存活着的坐标 for (x, y) in start_point: if 0 <= x + 1 <= size: # 前移,并存活 end_point.append((x + 1, y)) if 0 <= x - 1 <= size: # 后移,并存活 end_point.append((x - 1, y)) if 0 <= y + 1 <= size: # 上移,并存活 end_point.append((x, y + 1)) if 0 <= y - 1 <= size: # 下移,并存活 end_point.append((x, y - 1)) n -= 1 # 移动后,步数n-1 start_point = end_point.copy()# 移动后更新可能的起始坐标点 alive_number = len(end_point) alive_probability = alive_number / sum_probability return alive_probability