Code:
nums = [1, 2, 9, 11, 13]
for counter,num in enumerate(nums):
if counter == 0:
smallest = num
if counter == 1:
second = num
if counter > 1:
if second == smallest:
second = num
if num < second:
second = num
if second < smallest:
smallest, second = second, smallest
print(second)
Here is the algorithm of my approach :
- First initialise the smallest and second smallest numbers to be the first two inputs. That is,
Smallest=First_Input
and second_smallest = Second_Input
. These lines do that:
if counter == 0:
smallest = num
if counter == 1:
second = num
- Next See the third number. If the third number is smaller than the
second_smallest
number, then swap them. These lines do that
# This part is executed only when the counter exceeds 1
# That is, from the third input onwards.
if num < second:
second = num
- Now See the
smallest
and second_smallest
number. If second_smallest < smallest
, then swap them. These lines do that:
if second < smallest:
smallest, second = second, smallest
- Now, there will be an edgecase for inputs
[smallest, smallest, x, y, z]
. That is, when smallest number is repeated. It is because, the smallest
and second
variables store the first smallest and second smallest numbers respectively. But when the smallest number is repeated, they both store the same value(i.e the smallest
value). Therefore in this case, the actual second_smallest
value will not be able to replace the value in second
(since second
stores the smallest in this case)
To fix this, We have this line of code :
if second == smallest:
second = num