Implementing long division using a generator function in python

谁都会走 提交于 2019-12-02 01:43:01

Your main problem is that you output only a single value from the generator: next(gen). To output the whole generator, make a list from it's values: print(list(decimals(4))), or print it value by value:

for digit in decimals(4):
    print(digit)

To deal with endless generators (e.g., from a decimals(3) call), you can for example take only a limited amount of values from it with itertools.islice:

from itertools import islice
for digit in islice(decimals(3), 10):
    print(digit)

Also, I think there is something wrong with your algorithm. It doesn't seem to produce the correct results. I think, it should look something like this:

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

As a side note, this code may still be made shorter. For example:

def decimals(number):    
    dividend = 1
    while dividend:      
        yield dividend // number
        dividend = dividend % number * 10
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!