Printing Min1 and Min2 using Python

|▌冷眼眸甩不掉的悲伤 提交于 2020-05-30 08:05:20

问题


What am I missing in this code here so that it sets min1 and min2 to the two smallest numbers?

def test() : # do not change this line!
  list = [4, 5, 1, 9, -2, 0, 3, -5] # do not change this line!          
  min1 = list[0]
  min2 = list[1]
  #missing code here
  print(min1, min2)
  return (min1, min2) # do not change this line!
  # do not write any code below here  
test() # do not change this line!
  # do not remove this line!

回答1:


List does not sort elements in it implicitly. You have sort the list with sort() function. So before you take min1 and min2 from list you have sort list using sort function, you can do that with nameofyourlist.sort() and also you are not assigning return value of test() to any variable so you can avoid that line. Your final code can be as below

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

test()



回答2:


Just insert

list = sorted(list)

after this line

list = [4, 5, 1, 9, -2, 0, 3, -5] # do not change this line!



回答3:


If you are certain that there will be more than one value in the list then you can sort the list and assign first two items in min1 and min2.

def test() : # do not change this line!
  list = [4, 5, 1, 9, -2, 0, 3, -5] # do not change this line!
  list = sorted(list)
  min1 = list[0]
  min2 = list[1]
  #missing code here

  print(min1, min2)
  return (min1, min2) # do not change this line!
# do not write any code below here  

test() # do not change this line!
# do not remove this line!

Output:

-5 -2

Update

Updated the code. As we can't change the line with list declaration we can store the sorted list in next line and then assign first two values in two variables.




回答4:


You can add the line list.sort() to sort the list into ascending order, then your code will return the two smallest values.

def test() : # do not change this line!
  list = [4, 5, 1, 9, -2, 0, 3, -5] # do not change this line!
  list.sort()
  min1 = list[0]
  min2 = list[1]


来源:https://stackoverflow.com/questions/62043953/printing-min1-and-min2-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!