作为尝试理解生成器函数的练习,我试图编写一个模拟长除法的函数,并一次返回一位数。我写了这个函数,它似乎不起作用。但是,如果我在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()
答案 0 :(得分:3)
您的主要问题是您只从生成器输出一个值: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