Python:如何为函数的第二次调用存储函数中生成的值
我想创建一个随机数生成代码,输入“count”数,即在程序中被调用的次数。我想做的是,对于函数的偶数调用,我想创建两个随机数,它们是“y1,y2”,但是我只想输出y1,并且为函数的下一次调用保存y2。因此,对于奇数调用,函数将直接输出上一次调用的y2。谢谢你的帮助。迄今为止的守则:Python:如何为函数的第二次调用存储函数中生成的值,python,Python,我想创建一个随机数生成代码,输入“count”数,即在程序中被调用的次数。我想做的是,对于函数的偶数调用,我想创建两个随机数,它们是“y1,y2”,但是我只想输出y1,并且为函数的下一次调用保存y2。因此,对于奇数调用,函数将直接输出上一次调用的y2。谢谢你的帮助。迄今为止的守则: import random import math def gaussianRandom ( count): count += 1 if count%2 == 0: while (1): x1 = r
import random
import math
def gaussianRandom ( count):
count += 1
if count%2 == 0:
while (1):
x1 = random.uniform(-1, 1)
x2 = random.uniform(-1, 1)
r = x1**2 + x2**2
if (r < 1):
break
y1 = x1 * math.sqrt( (-2 * math.log(r)) / r )
y2 = x2 * math.sqrt( (-2 * math.log(r)) / r )
return y1
随机导入
输入数学
定义高斯随机数(计数):
计数+=1
如果计数%2==0:
而(一):
x1=随机均匀(-1,1)
x2=随机均匀(-1,1)
r=x1**2+x2**2
如果(r<1):
打破
y1=x1*math.sqrt(-2*math.log(r))/r)
y2=x2*math.sqrt(-2*math.log(r))/r)
返回y1
函数可以有属性
import random
import math
def gaussianRandom ( count):
count += 1
if count%2 == 0:
while (1):
x1 = random.uniform(-1, 1)
x2 = random.uniform(-1, 1)
r = x1**2 + x2**2
if (r < 1):
break
y1 = x1 * math.sqrt( (-2 * math.log(r)) / r )
gaussianRandom.y2 = x2 * math.sqrt( (-2 * math.log(r)) / r )
print(gaussianRandom.y2)
return y1
gaussianRandom.y2 = 99
print "y2", gaussianRandom(3)
print gaussianRandom(3)
print gaussianRandom(3)
随机导入
输入数学
定义高斯随机数(计数):
计数+=1
如果计数%2==0:
而(一):
x1=随机均匀(-1,1)
x2=随机均匀(-1,1)
r=x1**2+x2**2
如果(r<1):
打破
y1=x1*math.sqrt(-2*math.log(r))/r)
gaussianRandom.y2=x2*math.sqrt(-2*math.log(r))/r)
打印(gaussianRandom.y2)
返回y1
高斯随机数y2=99
打印“y2”,高斯随机(3)
打印高斯随机数(3)
打印高斯随机数(3)
y2 0.919282832355
-0.0887376744533
y2-1.71553385287
0.422645022058
y2-0.0668389339817
0.600351205084
您是否真的需要(或想要)告诉gaussianRandom()
您打算调用它多少次?这对我来说似乎有点限制
我认为这个问题最好用一个生成函数来解决。下面的代码显示了如何创建一个和如何使用它的两种方法。该生成器并没有实现高斯算法,而是简单地生成形式为6n±1的数字,所以您可以很容易地看到发生了什么
#! /usr/bin/env python
''' Generator demo '''
def gen():
x = 6
while True:
yield x-1
yield x+1
x += 6
def main():
g = gen()
for i in xrange(10):
print i, g.next()
print [(i, v) for i,v in zip(xrange(10), gen())]
if __name__ == "__main__":
main()
输出
0 5
1 7
2 11
3 13
4 17
5 19
6 23
7 25
8 29
9 31
[(0, 5), (1, 7), (2, 11), (3, 13), (4, 17), (5, 19), (6, 23), (7, 25), (8, 29), (9, 31)]
您可以使用memorization,但听起来这应该由类来解决。@DanielRoseman我也这么认为,当时正在考虑
lru\u cache
。请注意,此程序和问题中的程序都没有将计数作为静态变量/函数属性。因此,它可能无法完全满足s900n的要求。