简体   繁体   English

关于平均值、最大值和最小值的问题 function python

[英]Question about mean, max, and min function python

import statistics as stat
from statistics import mean
from random import seed, choice
from math import hypot
import random
from turtle import *
import statistics


seed(20190101)

def random_walk(n):
    x = 0
    y = 0
    for i in range(n):
        step = random.choice(["N","S","E","W"])
        if step == 'N':
            y = y + 1
        elif step == "S":
            y = y - 1
        elif step == "E":
            x = x + 1
        else:
            x = x - 1
    return (x,y)

for i in range(100):
    walk = random_walk(50)
    y = abs(walk[0]) + abs(walk[1])
    x = statistics.mean(y)

print(x)

please ignore the unused modules请忽略未使用的模块

So I am trying to get the mean of the numbrs from the function random_walk, but I am having a couple of issues.所以我试图从 function random_walk 中获取数字的平均值,但我遇到了几个问题。

First, I am supposed to be starting the program on a 0,0 grid.首先,我应该在 0,0 网格上启动程序。 I am trying to find the mean of the trials for 100 steps and 50 different styles from the seed provided.我试图从提供的种子中找到 100 个步骤和 50 个不同 styles 的试验平均值。 But it isn't working correctly, and I have no idea why..但它不能正常工作,我不知道为什么..

You are calculating the mean for each value returned from random_walk() inside the loop, over-ridding the previous value.您正在计算循环内从random_walk()返回的每个值的mean ,覆盖前一个值。 Change the loop to:将循环更改为:

all_steps = []
for i in range(100):
    walk = random_walk(50)
    all_steps.append(abs(walk[0]) + abs(walk[1]))
steps_mean = statistics.mean(all_steps) #Only after the loop
print(steps_mean)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM