Home > Enterprise >  My while loop runs infinite times when I think its not supposed to
My while loop runs infinite times when I think its not supposed to

Time:10-20

I was trying write a code that gives index of a minimum value of list one after other For example:

if list=[2,4,1,2,5]
         0 1 2 3 4

output:

[2,0,3,1,4]--> where each element in this corresponds to index of list variable

import math
list=[2,4,1,2,5]
a=[]
i=0
while(i <= (len(list)-1)):
    if(list[i]==min(list)):
        a.append(i)
        list[i]=math.inf
        i=-1
    i =1

print(a)

CodePudding user response:

The problem is that, when list becomes all inf, list[i]==min(list) is true because both list[i] and min(list) are inf. Then i resets to zero and you're in an infinite loop.

print(list, i, list[i], min(list), a)

Outputs:

[inf, inf, inf, inf, inf] 0 inf inf [2, 0, 3, 1, 4, 0, 0, 0, 0]

You can see that list a is being appended with zeroes.

"List" is actually a keyword in Python. Yes, it lets you use it, but that's bad form and you should use something like "lyst" or just "x" or something like that.

CodePudding user response:

Don't use 'list' to define your list. Use something else like 'my_list'.

you can use numpy library to generate an index of a minimum value of a list.

import numpy as np 

my_list = [2,4,1,2,5]
minimum_value_index = [np.argsort(my_list)[x] for x in range(len(my_list))]

print(minimum_value_index)

This will output as following:

[2, 0, 3, 1, 4]

Hope this helps.

  • Related