Finding two smallest values in a list

AlvaroMartinez

I am trying to return the two smallest values for a numeric list as a tuple. However the next code keeps returning first two values of a list.

def test(): 
  list = [4, 5, 1, 9, -2, 0, 3, -5] 
  min1 = list[0]
  min2 = list[1]

  length = len(list)
  
  for i in range(1, length):
    if list[i] < list[0]:
        if list[0] < list[1]:
            list[i] = list[1]
        else:
            list[i] = list[1] 
    else:
        if list[i] < list[1]:
            list[i] = list[1]
    print(min1, min2)

    return (min1, min2) 

test()

Console output:

4,5

Is there any way to do this by iterating?

Martijn Pieters

The variables min1 and min2 don't update, they are not references to the first and second element of the list, they are references to the values that were at indexes 0 and 1 when the assignment takes place. That you later change list[0] and list[1] doesn't matter.

In Python, both list indexes and variables are just references to the actual objects. Think of Python objects like balloons, and variables and indices are just labels tied to the a string attached to the balloon. You can attach multiple labels to the balloons, but if you than move the label to a different balloon, the other labels tied to the old balloon don't follow along.

Here, min1 and min2 were tied to balloons that already had the 0 and 1 index labels tied to them. Later on, when you assign to list[i], you retied a specific index label to another balloon, but the min1 and min2 labels didn't change.

As a side note, this part of your code has a rather obvious error:

if list[0] < list[1]:
    list[i] = list[1]
else:
    list[i] = list[1] 

Both branches do the exact same thing, assign list[1] to list[i].

You are otherwise doing completely incorrect assignments even if you hoped that changing list[0] and list[1] inside the loop would make a change to the values of min1 and min2, you are changing list[i], the other value in the list, the one that's supposed to be smaller.

So for i = 2, list[i] is list[2] and list[2] < list[0] is true (1 < 4), you then test if list[0] < list[1] (also true, 4 < 5), so you do list[i] = list[1], setting list[2] = 5, leaving list[0] set to 4, list[1] set to 5, and in effect throwing away the 1 value that was present at list[2] before.

Rather than compare with list[0] or list[1], have your loop update min1 and min2:

# min1 is always smaller than min2
min1, min2 = list[:2]
if min2 < min1:
    min1, min2 = min2, min1

for i in range(1, length):
    if list[i] < min1:
        min1 = list[i]
    elif list[i] < min2:  # but equal to or greater than min1!
        min2 = list[i]

I also made sure that min1 < min2 at the start, that makes the loop a lot simpler because if list[i] < min1 is not true then it can perhaps be smaller than min2 but you don't need to test against min1 a second time.

Note that we assign the list[i] values to min1 and min2 here, you want to update those two variables with the value you just tested, provided list[i] is indeed smaller than what you had before.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Finding the smallest number of steps between two points?

Finding the largest/smallest object in a python generator/list

Finding duplicate values in two arrays

Computing and removing the two smallest quantities in a list

How to find the smallest values of list of matrices by column

Finding the average of the three smallest values in range - Unexpected Compile Error

Finding the biggest and smallest values with most counts in histogram

Finding the smallest solution set, if one exists (two multipliers)

Using ortools to select the two smallest integer values in a list

Finding p% of smallest tensor values - TensorFlow 2.0

Finding smallest numbers Python numpy list

Two knapsacks with smallest delta in sum of values

finding smallest and second smallest number

Finding the 5 smallest numbers from a list in Python

Finding the smallest, largest, and middle values in Java

Haskell - finding smallest Element in list

Finding smallest differences of values of txt files

Rank A List Of Values (Largest to Smallest) Using VBA

How to get the rows with the smallest value in a list of values

Java finding number in list with smallest difference to given number

Finding a % from two values in postgresql

Finding smallest value in a linked list

Smallest difference pair of values between two list

Algorithm for finding the smallest lists that together make up the target list

Finding the smallest n values that are at least x apart in a list

Comparing two list values and finding only values from one list that do not exist in another

Finding the two clusters with smallest distance between a list of clusters

Finding nearest values in two vectors

Finding the smallest number in a python list with scientific notation

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive