
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to 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
- Related Articles
- Python program to find Largest, Smallest, Second Largest, and Second Smallest in a List?
- Python Program to Find the Second Largest Number in a List Using Bubble Sort
- C# program to find Largest, Smallest, Second Largest, Second Smallest in a List
- Python program to find the second largest number in a list
- Java program to find Largest, Smallest, Second Largest, Second Smallest in an array
- Program to find largest perimeter triangle using Python
- Python Program to Find the Largest value in a Tree using Inorder Traversal
- Python program to find largest number in a list
- C++ Program to find the second largest element from the array
- Swift Program to find the second largest element from the array
- C program to find frequency of each digit in a string
- Program to find Smallest and Largest Word in a String in C++
- C program to find the second largest and smallest numbers in an array
- Program to find super digit of a number in Python
- Python program to find the largest number in a list

Advertisements