假设某人位于N*N的区域中心,每次随机选择一个上下左右方向,他从中心处走出该区域所用的步数为一次模拟,求屡次模拟的平均数python
#coding=utf-8 import random #N = int(raw_input(u"请输入矩阵大小:")) #K = int(raw_input(u"请输入模拟次数:")) directions = {"W":"<","E":">","N":"∧","S":"v"} #生成初始矩阵函数 def get_matrix(n): matrix = [] for i in range(n): matrix.append(["." for i in range(n)]) return matrix #打印矩阵函数 def print_matrix(matrix): for item in matrix: print " ".join(item) #位置移动函数,坐标加减并返回 def move(x,y,direction): if direction == "W": y -= 1 if direction == "E": y += 1 if direction == "N": x -= 1 if direction == "S": x += 1 return x,y #单次模拟函数 def single_simulate(N): x, y = N/2,N/2 step = 0 matrix = get_matrix(N) matrix[x][y] = "o" print_matrix(matrix) print "steps %d; Y=%d,X=%d,N=%d; Status:IN" % (step,y,x,N) while 0 <= x <= N-1 and 0 <= y <=N-1: matrix[x][y] = "o" direction = random.choice(["W", "E", "N", "S"]) x,y = move(x,y,direction) step += 1 if 0 <= x <= N-1 and 0 <= y <=N-1: matrix[x][y] = directions.get(direction) print_matrix(matrix) print "steps %d; Y=%d,X=%d,N=%d; Status:IN" % (step,y,x,N) else: print_matrix(matrix) print "steps %d; Y=%d,X=%d,N=%d; Status:OUT" % (step,y,x,N) return step def simulate(N,K): count = [] for i in range(K): print "N=%d 时,开始第 %d 次模拟" % (N,i) step = single_simulate(N) count.append(step) print u"N=%d 时,第 %d 次模拟结束,共 %d 步走出" % (N,i+1,step) print u"N=%d 时,平均 %d 步走出" % (N,sum(count)/len(count)) simulate(11,2)