I have simple problem that I cannot seem to implement. I have a for loop in python that is iterated over a list of tuples and output a list of tuples. All I want to do is to pass the output list of tuples to the aforementioned for loop and keep doing that for a number of times (I decide that).
So, I have a set of individuals in a population, called gen1. It looks like this:
Generation 1 population is [(214, 66, 229, 87, 259), (256, 11, 249, 75, 242), (247, 41, 206, 4, 194), (214, 61, 172, 59, 225), (270, 78, 238, 69, 261), (235, 22, 175, 31, 213), (272, 37, 222, 80, 222), (233, 70, 207, 33, 218), (227, 38, 244, 47, 229), (264, 76, 246, 52, 239), (273, 2, 201, 10, 273), (215, 85, 205, 4, 199), (268, 9, 235, 51, 195), (236, 53, 198, 43, 273), (224, 27, 212, 29, 236), (275, 64, 190, 62, 257), (226, 23, 178, 44, 202), (219, 19, 196, 8, 227), (227, 60, 238, 15, 213), (216, 62, 185, 73, 192)]
Now, I write a for loop as follows:
for Po in gen1:
*do some operation, including crossover*
Ouptput gen2
I believe this is similar to recursive function in python, but instead of writing a function, I just want to update the for loop multiple times with its own output. How to achieve this?
CodePudding user response:
I mean you can just wrap a for loop around it:
n = ... # insert the number of generations
for i in range(n):
print(f"generation {i}:")
for Po in current_generation:
*do some operation, including crossover*
So after the loop current generation is the updated generation (as you've updated the values in that array). Though if you're unsure about the number of generations you can also use a while True:
loop and break
once you've reached a certain treshold or what do you intent to do with this?
CodePudding user response:
Short answer, use recursion, it is going to be much easier.
def recur(param, curr_depth=0, max_recur=20):
if(curr_depth >= max_recur or curr_depth > 900): ## Max Depth
return param
else:
## Do something
pass
## print Output
pass
return recur(param, curr_depth 1, max_recur)
Otherwise if you absolutely need for it not to use recursion, then use a while loop instead of a for, as a for loop cannot be changed mid-execution.
def fun(initial, max_depth=20):
finished = False
generation = initial
depth = 0
while(not finished):
for f in generation:
pass
# Assign the new result
generation = []
if(depth > max_depth or True): ## some condition indicating you are done
finished = True