Home > Mobile >  How to repeat a function till its return value matches its previous return value?
How to repeat a function till its return value matches its previous return value?

Time:09-26

I have a Python function that returns a value.

def population_gen(P)
    ...
    return fittest

Now, I need to write a piece of code that compares the "fittest" with last iteration of the function call population_gen(P) that returned "fittest" and stops when the current fittest becomes equal to the previous one.

What I have tried is the following:


def population_gen(P)
    ...
    return fittest

gen_count = 0
max_gen_count = 10
while gen_count <= max_gen_count:
    population_gen(Pop)
    gen_count  = 1

I can run this any number of times (11 in this case) and make sure that my code is working. But, I do not want to it run 11 times, rather keep the while loop running till the aforementioned condition is met. I also wanted to mention that this function generates a population from a given initial population. Then, I feed this function again with the population that it generates and successfully keep it running for as many times I want. But I cannot implement the condition of comparing the "fittest" value.

Please help. Thanks in advance!

CodePudding user response:

Use a new default variable set as maximum in the arguments. Like - def population_gen(P, prev_fit = 99999): if prev_fit < population_gen(P): return prev_fit

CodePudding user response:

I assume that you want to keep iterating through the loop if the current and last values of the function returned is not equal.

Theory: You can declare two variables, one inside loop and one outside. The work of inside one is to get the value of function returned by the function, and the outside one will be used to keep check of the previous value, so that it doesn't get lost (I mean the previous value here).

Now, you know, how simple it is, let's implement it. First, for the example, I would be creating a function that returns a random value from a list.

import random # Importing random module for help in choosing random value

def foo():
    _list = [1, 2, 3]
    return random.choice(_list)

Now, we have our example function, let's create a loop to keep check. NOTE: The type of loop you are using can be used, but the more efficient one is to use for loop, as you can use range function there as suggested by @Jab.

It's time to declare variables and the loop:

var = None # Outside the loop, will be used as a container for previous returned value

for _ in range(1, 12): # range(min. value, max. value [not included])
    a = foo() # Creating a variable 'a', that would be holding current returned value from the function
    if var is not None and a == var: # For first iteration, it would be None but the value will be assigned to 'var' in for it's next iteration and checking it whether the prev. and current values are equal or not
        break # Break the loop
    var = a # Assigns 'var' the value if the loop is still running

Now, the above example can be used as the answer. But, what if you want to check it? So, following is the code provided with the example for debugging purposes:

import random

def func():
    l = [1, 2, 3]
    val = random.choice(l)
    print(val) # Printing the value, for debugging purposes
    return val

var = None

for x in range(1, 12):
    a = func()
    if var is not None and a == var:
        print(f'\nSame values after {x} iterations') # It will show, after how many iterations the loop stopped
        break
    var = a

Now, I ran the above code 3 times, the following is the output:

OUTPUT:
>>> 3
>>> 3
>>>
>>> Same values after 2 iterations

>>> 2
>>> 3
>>> 2
>>> 2
>>>
>>> Same values after 4 iterations

>>> 2
>>> 2
>>>
>>> Same values after 2 iterations

I hope you understood the concept.

CodePudding user response:

Assuming you want to call the function population_gen until it's last two invocations return the same value. The output of population_gen becomes the input in the next iteration.

import random

def population(limit: int) -> int:
    return random.randint(1, limit)

prev = None
cur = population(10)

while prev != cur:
    prev = cur
    cur = population(prev)

print(prev)

CodePudding user response:

Using the builtin range function in python:

def population_gen(P):
    ...
    return fittest

for Pop in range(11):
    population_gen(Pop)
  • Related