python - How to find the two indexes from a list whos values are closest to zero -
i'm working on piece ga (fitness calculation actually) , need indexes of 2 values list whos values closest zero. have been looking hour on internet , though seems have become extremely close, , looks should work, testing print statements show code isnt working..
my process right is:
- find closest index , store it
- delete original array
- find new closest
this code in question:
closest = min(range(len(fitness_levels)), key=lambda i: abs(fitness_levels[i]-0)) fitness_levels.pop(closest) second_closest = min(range(len(fitness_levels)), key=lambda i: abs(fitness_levels[i]-0))
when fitness_levels = [-20, 23, -55, 11, 10, -18, -48, 16, -60, 20, 22, 16, 21, 66, 10, 46, -42]
granted numbers generated @ random.
like said, when checking print statements find method doensnt work in multiple ways, @ 1 point ended same index different values. have better workable way this? - python 2.7.x
side note- come php background, still warming python, syntax wrong...
while sorting abs
key work, that's nlogn solution. here's linear solution
fitness_levels = [-20, 23, -55, 11, 10, -18, -48, 16, -60, 20, 22, 16, 21, 66, 10, 46, -42] a,b = sorted(fitness_levels[:2], key=abs) # setting defaults. a<=b ia, ib = 0,1 # indices i,val in enumerate(fitness_levels[2:]): # use itertools.islice large lists (for constant space) if abs(val) < abs(a): b,a = a,val ib, ia = ia, elif abs(val) < abs(b): b = val ib =
Comments
Post a Comment