Home > other >  when i start for loop, the loop getting 0,0,1,2,3.. instead of 0,1,2,3
when i start for loop, the loop getting 0,0,1,2,3.. instead of 0,1,2,3

Time:11-04

if __name__ == '__main__':

    l=[]
    s=[]
    for _ in range(int(input())):
        name = input()
        score = float(input())
        l.append(name)
        s.append(score)
    mx=max(s[0],s[1])
    smin=min(s[0],s[1])
    n=len(s)
    for i in range(2,n):
        if(mx>s[i]):
            smin=mx
            mx=s[i]
        elif(s[i]<smin) and \
        max!=s[i]:
         smin=s[i]
    ind=smin
    sminval=s.index(ind)
    g=0
    for i in range(n):
        index_sec=s.index(s[i])
        print(index_sec)
        if(smin==s[i])and\
         sminval!=index_sec:
            x=s[i]   
        g=g 1
    y=l[sminval]

INPUT

5
Harry
37.21
Berry
37.210
Tina
37.2
Akriti
41
Harsh
39

OutPut

0
0
2
3
4    

while I get this type of index value(i). I can't able to locate correct index of element, I need explanation of why this is happening?

CodePudding user response:

This isn't very structured code, so it is hard to figure out what you really want it to do. I can't fix it for you. If you want to know what is happening, however, here is a walkthrough.

The line "index_sec=s.index(s[i])" is going to return the first index in list "s" that matches the value found at location i. This will be a unique index only if all the scores in s are unique.

However, Harry and Berry both have scores of "37.2". So when you look up the index of Harry's score, and you a lookup the value of Berry's score, you will not get Harry and Berry... you will get whichever one is first in the list... Harry in this case... both times.

To state it differently, when you take Harry's score and look it up, you get Harry. But when you take Berry's score and look it up, you also get Harry since Harry is the first item in the list that has that score. Since Harry is in index 0, that results in "0" followed by "0".

CodePudding user response:

Being completely honest, I have also no idea what is going one, what is the goal. All I can say is, you used the max() and min() method wrong. What you are looking for is the biggest and smallest value in between the first item of list s and the second item of s. What you meant is :

mx=max(s[0],s[len(s)-1])
smin=min(s[0],s[len(s)-1])

However, also this wouldn't be correct, as this would check only between the first and the last item. But you want the biggest out of all items. So the correct syntax is:

mx=max(s)
smin=min(s)

Besides that, I can't really help as I have no clue what is the scope of the code.

  • Related