The most occurring number in a string using Regex in python
Given a string str, the task is to extract all the numbers from a string and find out the most occurring element of them using Regex Python.
- It is guaranteed that no two element have the same frequency
- Examples:
Input :geek55of55geeks4abc3dr2 Output :55 Input :abcd1def2high2bnasvd3vjhd44 Output :2
Approach:Extract all the numbers from a string str using re.findall() function from regex library in python, and with the use of Counter function from collection library we can get the most occurred element.
Below is the Python implementation of above approach
# your code goes here# Python program to# find the most occurring elementimportrefromcollectionsimportCounterdefmost_occr_element(word):# re.findall will extract all the elements# from the string and make a listarr=re.findall(r'[0-9]+', word)# to store maxm frequencymaxm=0# to store maxm element of most frequencymax_elem=0# counter will store all the number with# their frequencies# c = counter((55, 2), (2, 1), (3, 1), (4, 1))c=Counter(arr)# Store all the keys of counter in a list in# which first would we our required elementforxinlist(c.keys()):ifc[x]>=maxm:maxm=c[x]max_elem=int(x)returnmax_elem# Driver programif__name__=="__main__":word='geek55of55gee4ksabc3dr2x'print(most_occr_element(word))Output:55
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


