作为尝试理解生成器函数的练习,我正在尝试编写一个模拟长除法并一次返回一位数字的函数。我已经写了这个函数,但它似乎不起作用。但是,如果我在 shell 中逐行执行它,它就会完全按照我想要的方式执行,所以我不确定接下来要做什么。我在这里阅读了互联网上有关生成器功能的帖子:
据我所知,我只是用yield语句替换了return语句。难道不是这样吗?有人可以告诉我我做错了什么吗?如有任何帮助,我们将不胜感激。
def decimals(number):
"""
Takes a numnber and generates the digits of 1/n.
"""
divisor = number
dividend = 1
while dividend % divisor != 0:
#Floor division is the // operator
quotient = divisor // dividend
remainder = dividend % divisor
temp = quotient * divisor
if remainder != 0 :
temp = quotient * divisor
if temp > dividend:
dividend = dividend * 10
dividend = dividend - temp
else:
dividend = dividend - temp
yield quotient
def main():
gen = decimals(4)
print(next(gen))
if __name__ == "__main__":
main()
最佳答案
您的主要问题是您仅从生成器输出一个值:next(gen)
。要输出整个生成器,请根据其值创建一个列表:print(list(decimals(4)))
,或按值打印它:
for digit in decimals(4):
print(digit)
要处理无尽的生成器(例如,来自 decimals(3)
调用),您可以使用 itertools.islice
从中仅获取有限数量的值>:
from itertools import islice
for digit in islice(decimals(3), 10):
print(digit)
另外,我认为你的算法有问题。它似乎没有产生正确的结果。我想,它应该看起来像这样:
def decimals(number):
"""
Takes a number and generates the digits of 1/n.
"""
divisor = number
dividend = 1
remainder = 1
while remainder:
#Floor division is the // operator
quotient = dividend // divisor
remainder = dividend % divisor
if remainder < divisor:
dividend = remainder * 10
else:
dividend = remainder
yield quotient
顺便说一句,这段代码可能仍然会更短。例如:
def decimals(number):
dividend = 1
while dividend:
yield dividend // number
dividend = dividend % number * 10
关于python - 使用Python中的生成器函数实现长除法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29424349/