移動後存活概率
阿新 • • 發佈:2020-08-11
問題見圖片
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