It was working properly,but while tried with
my_nums = [16,5,7,9,12]
it's not working.
def get_second_largest(nums):
largest = nums[0]
second_largest = nums[0]
for i in range(1,len(nums)):
if nums[i] > largest:
second_largest = largest
largest = nums[i]
elif nums[i] > second_largest:
second_largest = nums[i]
return second_largest
my_nums = [16,5,7,9,12]
second_largest = get_second_largest(my_nums)
print("Second highest number is : ",second_largest)
CodePudding user response:
my_nums = [16, 5, 7, 9, 12]
my_nums.remove(max(set(my_nums))) #removing the maximum element
print(max(my_nums)) #printing the second largest element
One more method
CodePudding user response:
Sort the list (default ascending) and return the penultimate element from the output of the sort.
def get_second_largest(nums):
return None if len(nums) < 2 else sorted(nums)[-2]
CodePudding user response:
There is an easier way to do this with sort
:
my_nums = [16, 5, 7, 9, 12]
my_nums.sort(reverse=True) # Descending order
print(my_nums[1]) # Output: 12
If you want to cope without sorting, as someone commented above you need to set the initial value of the variables outside of the list scope. -1
will suffice with your example, but a better way to do it is setting the starting value so that there is nothing smaller: float('-inf')
.
CodePudding user response:
Your only mistake is to set both largest
and second_largest
to nums[0]
, which in the example happens to be the largest number available - so it will never be replaced.
As a side note, why don't you iterate directly on the list items instead of an index?
So your code may become like this:
def second_largest(nums):
largest = second_largest = 0 #or -math.inf if you want to account for any possible value
for n in nums:
if n > largest:
second_largest = largest
largest = n
elif n > second_largest:
second_largest = n
return second_largest
Finally, this could be generalized to find the k-th largest number (though sorting would probably be a better strategy at this point):
def kth_largest(nums, k):
largest_nums = [0 for x in range(k)]
for n in nums:
for i,large in enumerate(largest_nums):
if n > large:
largest_nums.insert(i,n)
del largest_nums[-1]
break
return largest_nums[k-1]
CodePudding user response:
You can use np.sort() to sort the array and access the second last element.
It looks something like this:
my_nums_sorted = np.sort(np.array(my_nums)) # Convert to np.array and sort
second_largest = my_nums_sorted[-2]