How to find the second smallest value of a python array without using built-in functions?

Asked

Viewed 1,032 times

1

I’m new to programming and I’m having trouble creating a code that returns the second lowest value of a array, ex:

array = [2, 3, 6, 6, 5]

return 3

I am in that phase of practicing the logic of programming, because I already understand the whole basic set of logic, but, as I have little practice in applying, I still run into problems that I believe are simple, finally, I hope you understand.

  • Why returns 5 if the second minor would be 3?

  • was bad Anderson Carlos, that’s right, has to return the 3, lack of attention my, thanks! , kkkkkkkkkkk

2 answers

1


def segMenor(numeros):
     m1, m2 = float('inf'), float('inf')
     for x in numeros:
         if x <= m1:
             m1, m2 = x, m1
         elif x < m2:
             m2 = x
     return m2

 print segMenor([2, 3, 6, 6, 5])
  • Oops, I saw right, corrected.

  • Now we just need to explain your code :D

  • 1

    M1 and m2 will receive 5 and 6, x = 2, ai it checks if 2 <= 5, yes, then M1 = 2 and m2 = 6, ai it starts again with x = 3 now, until qd x = 6 and m2 = 5, ai falls in the second if (6 > 5) and the m2 gets 5. Difficult to explain pq is very complex, but if you do on paper will understand better.

  • oi Allan, man I’m not able to understand how this assignment of values for M1 and m2 works, how the variables gets a float function with strings inside (I didn’t know this was possible), and how does the code know that M1 is worth 5?, pq looking at the code, for me both M1 and m2 only have a float function with strings inside, how can a float function store strings? and how it can have a value in the first pass of if if it has no value assigned to variable M1, only a float function,.

  • 1

    Good afternoon, M1 and m2 does not receive a number from the list, but I used the list for you to understand easier. This inf ( is infinite - a value greater than any other value , ñ a string). At the beginning will always fall in the first if, dai x will receive a value from the list, there begins the truth. Pq inf will always be higher q any other number. Dai M1 will receive the x, then it compares again, and so it goes. It only uses inf the first time, then x gets value from the list.

0

First you can use the SET to organize the data, ensuring the ordination and the absence of duplicate copies.

    array = [2, 3, 6, 6, 5]
    copia = set(array)

The content of the copy variable is "[2,3,5,6]", that is, we guarantee that the second value is always the second lowest.

After this you can print the desired value as follows:

   print (list(copia)[1]) 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.