I got this exercise: Take an unknown number of positive integers as input. Assume that the first number is always smaller than the second, all numbers are unique and the input consists of at least three integers. Print the second smallest integer. I came up with this code:
list=[10,12,1,3,2]
#find smallest number
if list[0]>list[1]:
smallest = list[1]
else:
smallest = list[0]
if smallest>list[2]:
smallest = list[2]
if smallest > list[3]:
smallest = list[3]
if smallest > list[4]:
smallest = list[4]
#remove smallest number from list
list.remove(smallest)
#find smallest number in new list
if list[0]>list[1]:
second_smallest = list[1]
else:
second_smallest = list[0]
if second_smallest > list[2]:
second_smallest = list[2]
if second_smallest > list[3]:
second_smallest = list[3]
print(second_smallest)
What can I do to simplify it? Thanks!
CodePudding user response:
You can use python's list sort method:
my_list = [10, 12, 1, 3, 2]
my_list.sort()
print(my_list[1])
CodePudding user response:
sample_list = [10, 12, 1, 3, 2]
smallest = sample_list[0]
second_smallest = sample_list[1]
for i in range(2, len(sample_list)):
if sample_list[i] < smallest:
smallest = sample_list[i]
elif sample_list[i] < second_smallest:
second_smallest = sample_list[i]
>>> print(smallest)
>>> 1
>>> print(second_smallest)
>>> 2
CodePudding user response:
numbers = ...
smallest = numbers[0]
second_smallest = numbers[1]
for index in range(2, len(numbers)):
number = numbers[index]
if number < smallest:
second_smallest = smallest
smallest = number
elif number < second_smallest:
second_smallest = number
print(second_smallest)
This solution leverages the assumption that the first two numbers are in order. Of course if you're able to use python built-ins you can use this code:
print(sorted(numbers)[1])
CodePudding user response:
nsmallest
in heapq
should be what you need:
>>> lst = [2, 21, 20, 63, 53, 0, 38, 20, 11, 26]
>>> from heapq import nsmallest
>>> nsmallest(2, lst)[-1]
2
CodePudding user response:
You can first get the smallest number in the list with the min
function.
num_list = [10, 12, 1, 3, 2]
min_num = min(num_list)
Then, make a new list by filtering out min_num
so that the smallest number of the filtered_list
is actually the second-smallest value of the initial list.
filtered_list = [n for n in num_list if n != min_num]
print(min(filtered_list))