samedi 3 octobre 2020

How to stop a generator once target is matched?

Attempting to create a generator that generates a random set of numbers in a specified range and then stops once a specified target number is generated. The number of attempts to get to that number would be printed. If the number is not generated within the specified number of attempts, the user would get a separate prompt. Here's what I have so far:

try:
    min_value = int(input("Enter the minimum value for your random generator: "))
    max_value = int(input("Enter the maximum value for your random generator: "))
    target = int(input("Enter the target value you are trying to find: "))
    max_attempts = int(input("Enter the maximum number of attempts to find the target before stopping generation: "))
except ValueError:
    print("Please enter an integer value for your input!")

def find_target(target: int, min_value: int, max_value: int, max_attempts: int) -> Optional[int]:
    # Start counter for number of attempts
    j = 0
    while j in range(max_attempts):
        #Increment the attempts counter
        j += 1
        for k in range(min_value, max_value):
            if not target:
                yield k

gen = find_target(target, min_value, max_value, max_attempts)

while True:
    print(next(gen))

Once the target was found, ideally something like this would happen:

# Stop the generator
print("Target acquired! It only took ", j, "tries to find the target!")
gen.close()

if find_target(target, min_value, max_value, max_attempts) is None:
    print("Could not find target within the max number of attempts. Maybe better luck next time?")

Right now the generator just stops immediately (I'm guessing it has something to do with how if not target is specified). How could I get the logic for this to work?




Aucun commentaire:

Enregistrer un commentaire