Last Updated : 10 Apr, 2025
We are given a string that contains a mix of text and numbers, and our task is to find the number that appears most frequently. For example, in the string "I have 3 apples, 12 oranges, 3 bananas, and 15 3", the number "3" appears the most. To solve this efficiently, we can use regular expressions (Regex) in Python to extract all numbers from the string and then determine which one occurs most often. Let's explore an efficient approach to solve this.
Step-by-Step Algorithm
import re
from collections import Counter
s = 'geek55of55gee4ksabc3dr2x'
# Extract digit sequences
a = re.findall(r'\d+', s)
# Count frequencies
freq = Counter(a)
# Track max frequency and number
mx, res = 0, 0
for x in freq:
if freq[x] >= mx:
mx = freq[x] # update max frequency
res = int(x) # update result with larger num in tie
print(res)
Explanation:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4