list - Finding an index in range of values between 0-100 in Python -
this 2 part question, have make selection of 2 indexes via random range of number of integers in list. can't return both if they're both in same range well
selection1 = random.randint(0,100) selection2 = random.randint(0,100)
for sake of argument, say:
selection1 = 10 selection2 = 17 , list [25, 50, 75, 100]
both return index of 0 because fall between 0-25
so both fall first index range, problem i'm having issues trying fit range (ie: 0-25) return first index (return list[0])
what syntax type of logic in python?
i'm sure can figure out how return different indexes if fall in same range, loop reset loop if can advice on wouldn't hurt.
i'll give code i'm working right guideline. @ bottom i'm struggling.
code here
def roulette_selection(decimal_list, chromosome_fitness, population): percentages = [] in range(population): result = decimal_list[i]/chromosome_fitness result = result * 100 percentages.append(result) print(percentages) range_in_fitness = [] current_percent = 0 in range(population): current_percent = percentages[i] + current_percent range_in_fitness.append(current_percent) parent1 = random.randint(0, 100) parent2 = random.randint(0, 100) in range(population): if parent1 >= range_in_fitness[i] , parent1<=range_in_fitness[i+1]: print(parent1, parent2) print(range_in_fitness)
if list of ranges sorted, or acceptable sort it, , contiguous (no gaps), can use python's bisect
module in efficient manner. example:
>>> l = [25, 50, 75, 100] >>> import bisect >>> bisect.bisect(l, 10) 0 >>> bisect.bisect(l, 17) 0 >>> bisect.bisect(l, 55) 2 >>> bisect.bisect(l, 25) 1
bisect returns index of input number should fall list maintain sort order. note little confusing think @ first; in case of 55
above, returns 2
because should inserted @ index 2 falls between current values @ indices 1
, 2
. if give number on range boundary, 'fall right', evidenced bisect(l,25)
example.
the linked documentation includes set of recipes searching through sorted lists using bisect
.
Comments
Post a Comment