如果不使用yield,这该怎么写呢?
我曾多次尝试替换yield,但都失败了,但我似乎没有成功,目标是拥有相同的功能,但没有yield。
def calcPi(limit): # Generator function
"""
Prints out the digits of PI
until it reaches the given limit
"""
q = 1
r = 0
t = 1
k = 1
n = 3
l = 3
decimal = limit
counter = 0
while counter != decimal + 1:
if 4 * q + r - t < n * t:
# yield digit
yield n
# insert period after first digit
if counter == 0:
yield '.'
# end
if decimal == counter:
print('')
break
counter += 1
nr = 10 * (r - n * t)
n = ((10 * (3 * q + r)) // t) - 10 * n
q *= 10
r = nr
else:
nr = (2 * q + r) * l
nn = (q * (7 * k) + 2 + (r * l)) // (t * l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
添加了人们在评论中要求的完整功能,
I've tried and failed multiple times trying to replace yield, but I don't seem to be successful, the goal is to have the same function, without yield.
def calcPi(limit): # Generator function
"""
Prints out the digits of PI
until it reaches the given limit
"""
q = 1
r = 0
t = 1
k = 1
n = 3
l = 3
decimal = limit
counter = 0
while counter != decimal + 1:
if 4 * q + r - t < n * t:
# yield digit
yield n
# insert period after first digit
if counter == 0:
yield '.'
# end
if decimal == counter:
print('')
break
counter += 1
nr = 10 * (r - n * t)
n = ((10 * (3 * q + r)) // t) - 10 * n
q *= 10
r = nr
else:
nr = (2 * q + r) * l
nn = (q * (7 * k) + 2 + (r * l)) // (t * l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
Added the full function as people were asking for it in the comments,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需定义一个列表并收集数字:
Just define a list and collect the digits: