python小練習1:隨機漫步

 假設某人位於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)
相關文章
相關標籤/搜索