Program to find second largest digit in a string using Python

PythonServer Side ProgrammingProgramming

Suppose we have an alphanumeric string s, we have to find the second largest numerical digit that appears in s, if there is no such string then return -1.

So, if the input is like s = "p84t3ho1n", then the output will be 4 as the digits are [1,3,4,8], so second largest digit is 4.

To solve this, we will follow these steps −

  • lst := a new set

  • for each let in s, do

    • if let is not alphabetic, then

      • insert let as integer in lst

  • if size of lst <= 1, then

    • return -1

  • return the second last element after sorting lst

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(s):
   lst = set()
   for let in s:
      if not let.isalpha():
         lst.add(int(let))
   if len(lst) <= 1:
         return -1
   return sorted(list(lst))[len(lst) - 2]
s = "p84t3ho1n"
print(solve(s))

Input

"hello", "hlelo"

Output

True
raja
Published on 27-May-2021 14:41:36
Advertisements