Search code examples
pythonpython-3.xrandomiteratorgenerator

How do I let my generator call infinitely into the function


I am new to generators and I am trying to make the below code work where my generator should send a random number to my function and check if it matches the target and return the number of count to make this match, when I run the code it justs stops iteration, where am I going wrong?

def generator(min_val: int, max_val: int) -> Iterator[int]:
    

    yield random.randint(min_val,max_val)


def find_target(target: int, min_val: int=0, max_val: int=10, max_attempts: int=100):
    
    i=1
    cnt=1

    g =  generator(0,10)
    while i<100:
        a = next(g)
        if g==target:
            return cnt
        else:
            cnt+=1
        i+=1
    if i >=100:
        return None

Solution

  • To make an infinite generator you need to have an infinite loop yielding values. However that's not the only problem with your code — the find_target() has multiple errors (and ignores some of the arguments passed to it).

    The following corrects those issues, too, plus shows how to type-hint the return value of the find_target() function.

    import random
    from typing import Iterator, Optional
    
    
    def generator(min_val: int, max_val: int) -> Iterator[int]:
        while True:
            yield random.randint(min_val, max_val)
    
    def find_target(target: int, min_val: int=0, max_val: int=10,
                        max_attempts: int=100) -> Optional[int]:
        g = generator(min_val, max_val)
        for cnt in range(max_attempts):
            if next(g) == target:
                return cnt+1
        else:
            return None
    
    
    print(find_target(42, 0, 100, 1000))