Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find second largest digit in a string using Python
When working with alphanumeric strings, we often need to extract and analyze the numerical digits. This program finds the second largest digit in a string, returning -1 if there aren't enough unique digits.
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.
Algorithm
To solve this, we will follow these steps −
Create a set to store unique digits
-
For each character in the string, do
If character is a digit, add it to the set as integer
-
If size of set <= 1, then
Return -1 (not enough unique digits)
Sort the digits and return the second largest
Example
def solve(s):
digit_set = set()
for char in s:
if char.isdigit():
digit_set.add(int(char))
if len(digit_set) <= 1:
return -1
sorted_digits = sorted(list(digit_set))
return sorted_digits[-2] # Second largest
# Test with example
s = "p84t3ho1n"
result = solve(s)
print(f"Input: {s}")
print(f"Second largest digit: {result}")
Input: p84t3ho1n Second largest digit: 4
Testing Edge Cases
Let's test with different scenarios ?
def solve(s):
digit_set = set()
for char in s:
if char.isdigit():
digit_set.add(int(char))
if len(digit_set) <= 1:
return -1
sorted_digits = sorted(list(digit_set))
return sorted_digits[-2]
# Test cases
test_cases = ["p84t3ho1n", "hello", "a1b2c", "987654321", "aaa1aaa"]
for test in test_cases:
result = solve(test)
print(f"'{test}' ? {result}")
'p84t3ho1n' ? 4 'hello' ? -1 'a1b2c' ? 1 '987654321' ? 8 'aaa1aaa' ? -1
How It Works
The solution uses a set to automatically handle duplicate digits. We iterate through each character, check if it's a digit using isdigit(), and add it to our set as an integer. Finally, we sort the unique digits and return the second largest element using index [-2].
Conclusion
This program efficiently finds the second largest digit by using a set to eliminate duplicates and sorting to find the required element. It handles edge cases by returning -1 when there aren't enough unique digits.
