Program to find the most frequent number in the given string using regex

by | Dec 26, 2020 | Python Programs

Home » Python » Python Programs » Program to find the most frequent number in the given string using regex

Introduction

The task is to find the most occurring number in the given string using regex expression.

find the most frequent number in the given string

Program

from collections import Counter
import re  
    
def frequent_no(ip_str):
    arr = re.findall(r'[0-9]+', ip_str)
    max_freq = 0
    ele = 0
    count = Counter(arr)
    for i in list(count.keys()):
        if count[i]>=max_freq:
            max_freq = count[i]
            ele = int(i)
    return ele
 
       
ip_str = input("Enter the string: ")
print("The most frequent number in the string {0} is {1}". format(ip_str, frequent_no(ip_str)))

Output

find the most frequent number in the given string Output

Explanation

In the above python code our approach is:

  • Extract all the numbers from the given string using regex expression.
  • Using Counter() function we stored all the numbers with their frequency of occurrence.
  • And then we used loop on counter() result to get the most occurred number in the string.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author