Swayam Shah
Swayam Shah

Reputation: 111

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

Upvotes: 0

Views: 83

Answers (3)

martineau
martineau

Reputation: 123473

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))

Upvotes: 1

quamrana
quamrana

Reputation: 39374

You seem to have lots of things wrong here.

(but starting with stealing from @Blckknght)

import random

def generator(min_val, max_val):
    while True:
        yield random.randint(min_val, max_val)


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

    g = generator(min_val, max_val)  # pass params onto generator
    for _ in range(max_attempts):    # loop around max_attempts times
        a = next(g)
        if a == target:              # if a result is the target
            cnt += 1                 # increment the count
    return cnt

print(find_target(5))

Sample output:

11

Upvotes: 1

Blckknght
Blckknght

Reputation: 104722

If you want your generator to be infinite, write an infinite loop. The simplest one is probably:

def generator(min_val: int, max_val: int) -> Iterator[int]:
    while True:
        yield random.randint(min_val,max_val)

Upvotes: 1

Related Questions