是否有一种pythonic方法来构建包含某些函数的运行平均值的列表?
在阅读了一篇关于火星人,黑匣子和柯西分布的有趣小块之后,我认为自己计算Cauchy分布的平均值会很有趣:
import math
import random
def cauchy(location, scale):
p = 0.0
while p == 0.0:
p = random.random()
return location + scale*math.tan(math.pi*(p - 0.5))
# is this next block of code a good way to populate running_avg?
sum = 0
count = 0
max = 10
running_avg = []
while count < max:
num = cauchy(3,1)
sum += num
count += 1
running_avg.append(sum/count)
print running_avg # or do something else with …Run Code Online (Sandbox Code Playgroud) 我是斯卡拉新手,刚开始学习这门语言.
我从Project Euler页面解决了问题8.
代码看起来像这样(我删除了读取输入文件所需的所有代码):
def max(n1: Int, n2: Int): Int = Math.max(n1, n2)
def max_product(digits: List[Int], num: Int): Int = {
def max_core(lst: List[Int], curr_max: Int): Int = lst match {
case a if lst.length >= num =>
max_core(a.tail, max(lst.slice(0, num).reduceLeft(_*_), curr_max))
case _ => curr_max
}
max_core(digits, 0)
}
println(max_product(1::2::3::4::2::3::Nil, 2))
它工作正常,结果是正确的.但是,我对这个解决方案并不完全满意.我不喜欢max_core子功能,并且感觉它可以改进.我对FP的理解是,你应该迭代一个列表,切片似乎不是这里的方式.
问题是:如何?