Unexpected order of operators in a for loop iteration using zip() to iterate over two elements in parallel [closed]
I'm working on the knapsack problem in Python using genetic algorithm and I've stumbled upon a strange phenomenon. From what I've found iteration over two elements in parallel should work like this:
foo = (1, 2, 3)
bar = (4, 5, 6)
for f,b in zip(foo,bar):
print(f,b)
Resulting in:
1 4
2 5
3 6
Yet in my case it seems to work in an inverted way using f to iterate over bar and b over foo. Is there a way to make it work like in the example above? Though im mostly interested in understanding why it works the way it's working. Weight function is supposed to return the weight of the chosen set of items. First one works just fine, second one returns 0. My code:
def weight1(genome: Genome, things: [Thing]):
return sum([t.weight for t,g in zip(genome,things) if g==1])
def weight2(genome: Genome, things: [Thing]):
return sum([t.weight for t,g in zip(things,genome) if g==1])
item_weight_test1 = weight1(things,population[0])
item_weight_test2 = weight2(things,population[0])
where things is a list of named touples:
Thing = namedtuple('Thing', ['name', 'value', 'weight'])
and population is a list of integers containing ones and zeroes
Genome = List[int]
Population = List[Genome]
source https://stackoverflow.com/questions/71040359/unexpected-order-of-operators-in-a-for-loop-iteration-using-zip-to-iterate-ove
Comments
Post a Comment