Implement long division using generator function in python

As an exercise, in order to try to understand the functions of the generator, I am trying to write a function that simulates a long division and returns the digit number one at a time. I wrote this function and it does not work. However, if I go through it line by line in the shell, it does exactly what I want to do this, I'm not sure what to do next. I read the posts on the internet about generator functions here:

and from what I understand, I just replace the return statement with the yield statement. Is that not so? Can someone please tell me what I am doing wrong? Any help is appreciated.

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()
+2
1

, : 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
+3

All Articles