Friday, December 27, 2024
Google search engine
HomeLanguagesPython program to find maximum uppercase run

Python program to find maximum uppercase run

Giving a String, write a Python program to find the maximum run of uppercase characters.

Examples:

Input : test_str = ‘GeEKSForGEEksISBESt’ 
Output : 5 
Explanation : ISBES is best run of uppercase.

Input : test_str = ‘GeEKSForGEEKSISBESt’ 
Output : 10 
Explanation : GEEKSISBES is best run of uppercase. 

Method : Using isupper() + loop

In this, we update the maximum run when non-uppercase is encountered otherwise counter is incremented if the character is uppercase.

Python3




# Python3 code to demonstrate working of
# Maximum uppercase run
# Using isupper() + loop
 
# initializing string
test_str = 'GeEKSForGEEksIsBESt'
 
# printing original string
print("The original string is : " + str(test_str))
 
cnt = 0
res = 0
for idx in range(0, len(test_str)):
     
    # updating run count on uppercase
    if test_str[idx].isupper():
        cnt += 1
         
    # on lowercase, update the maxrun
    else :
      if res < cnt :
        res = cnt
        cnt = 0
      else :
        cnt = 0
if test_str[len(test_str) - 1].isupper():
    res = cnt
 
# printing result
print("Maximum Uppercase Run : " + str(res))


Output:

The original string is : GeEKSForGEEksISBESt
Maximum Uppercase Run : 5

The time and space complexity for all the methods are the same:

Time Complexity : O(n)
Auxiliary Space : O(n)

Method : Using re

Another approach to solve this problem would be to use the built-in re module in Python to find all the substrings of consecutive uppercase characters in the given string and then find the maximum length among them. Here is the implementation of the same:

Python3




import re
 
def max_uppercase_run(test_str):
    # Find all substrings of consecutive uppercase characters
    uppercase_runs = re.findall(r'[A-Z]+', test_str)
    # Find the maximum length among the substrings
    return max(len(run) for run in uppercase_runs) if uppercase_runs else 0
 
# test cases
test_str = "GeEKSForGEEksISBESt"
print("The maximum uppercase run is:", max_uppercase_run(test_str))
 
test_str = "GeEKSForGEEKSISBESt"
print("The maximum uppercase run is:", max_uppercase_run(test_str))


Output

The maximum uppercase run is: 5
The maximum uppercase run is: 10

The time complexity of this approach is O(n), where n is the length of the input string test_str. The space complexity is O(n) as we are storing the substrings in the uppercase_runs list.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments