How can I search for the three maximum elements of a list and replace it at same index with its result when divided by 2.
Please what am I doing wrong:
input is: 2 5 8 19 1 15 7 20 11
output should be : 2 5 8 9.5 1 7.5 7 10 11
Index out of range is the result displayed
def numberInput(line):
lineInput = [int(i) for i in line.split()]
min1 = min(lineInput)
for j in range(len(lineInput)):
if lineInput[j]>min1 and lineInput[j] > lineInput[j+1]:
max1 = lineInput[j]/float(2)
else:
max1 = lineInput[j]/float(2)
lineInput[j] = max1
lineInput[j] = max1
return(lineInput)
number = '2 5 8 19 1 15 7 20 11'
print(numberInput(number))
lineInput[j+1]is outside the list. You need to userange(len(lineInput)-1)heapq.nlargestshould be somewhat faster; it'sO(n log k)(wherekis 3 in this case) rather than theO(n log n)you pay on a complete sort (whether it's faster in practice would require testing;sortedis implemented in C,nlargestis Python with C-accelerated helpers, so it's slower than big-O might lead you to believe).