from random import choice
def escolher():
a = choice([[10.00,90.00,30.00,40.00],[50.00,60.00,90.00,80.00]])
fitness_1_temp = 0
for i in a:
for j in i:
#---------------^^^
if j <= 85.0:
fitness_1_temp += j
else:
fitness_1_temp -= j
return fitness_1_temp
print (escolher())
See in the code above, the part highlighted by the comment. You’re trying to iterate on a value of type float
. Besides, it doesn’t make much sense to do both loop
, only one is able to solve the sum.
Let’s say choice
returned the first list:
a = [10.00,90.00,30.00,40.00]
Iterating for i in a
, i
will have the values 10.0, 90.0, 30.0 and 40.0, depending on the current iteration. From this value, you can already do the operation:
fitness_1_temp = (fitness_1_temp+i) if i <= 85.0 else (fitness_1_temp-i)
For the given examples, it will be returned -10.0 when the first list is considered or 100.0 when the second.
See working on Repl.it, in the Ideone, and in the Github Gist.
Workaround
When we want to reduce a list to a single value, we can use the operation reduce
. In Python 2, reduce
is a built-in Function, while in Python 3 it was incorporated into the module functools
. Both have the same format:
reduce(function, iterable[, initializer])
In Python 2:
from random import choice
def escolher():
a = choice([[10.00,90.00,30.00,40.00],[50.00,60.00,90.00,80.00]])
fitness_1_temp = reduce(lambda x, y: (x+y) if y <= 85.0 else (x-y), a, 0)
return fitness_1_temp
print (escolher())
In Python 3:
from random import choice
from functools import reduce
def escolher():
a = choice([[10.00,90.00,30.00,40.00],[50.00,60.00,90.00,80.00]])
fitness_1_temp = reduce(lambda x, y: (x+y) if y <= 85.0 else (x-y), a, 0)
return fitness_1_temp
print (escolher())
Same solution, only need to import module function functools
.
It worked perfectly buddy. Thank you very much!
– Danilo
@Danilo, I added an alternative solution using the function
reduce
. Take a look, it’s worth it.– Woss
I saw your solution with reduce and it is magnificent. You helped me immensely. You have no idea! A strong hug friend.
– Danilo