如果不使用 yield,这将如何编写?
How would this be written without using 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
添加了人们在评论中要求的完整功能,
只需定义一个列表并收集数字:
def calcPi(limit): # Generator function
"""
Collects the digits of PI
until it reaches the given limit
"""
pi = []
...
while ...:
...
# yield n
pi.append(n)
...
#break
return pi
我尝试过多次尝试替换 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
添加了人们在评论中要求的完整功能,
只需定义一个列表并收集数字:
def calcPi(limit): # Generator function
"""
Collects the digits of PI
until it reaches the given limit
"""
pi = []
...
while ...:
...
# yield n
pi.append(n)
...
#break
return pi