
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Second Largest Digit in a String Using Python
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
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
Advertisements