3 回答

TA贡献1818条经验 获得超3个赞
另一个解决方案很棒。这是一种不同的方法:
import numpy as np
def RVs():
# s = 0
s = 1
f = 0
while True: # will always run the first time...
z = np.random.random()
if z <= 0.5:
x = -1
else:
x = 1
s = s + x
f = f + 1
if s == 0: break # ... but stops when s becomes 0
return(f)
RVs()
注意:return(f)需要在原始代码中缩进才能在RVs函数内。

TA贡献1799条经验 获得超9个赞
据我所知,您正在尝试模拟 do while 循环,该循环将至少运行一次(并且您希望 s 的起始值为 0)
如果是这种情况,您可以无限地运行循环并在条件为真时中断循环。例如:
while True:
#code here
if (s != 0):
break
这将至少运行一次您的循环,并在最后再次运行循环,直到您的条件通过

TA贡献1772条经验 获得超6个赞
Python 没有 do.... while() 和其他语言一样。所以只需使用“第一次”操作符。
import numpy as np
def RVs():
s = 0
t = 1 # first time in loop
f = 0
while s!=0 or t==1:
t = 0 # not first time anymore
z = np.random.random()
if z<=0.5:
x = -1
else:
x = 1
s = s + x
f = f + 1
return(f)
RVs()
添加回答
举报