Largest Number Groupings in String in Python

0 min read 135 words

The challenge

You are be given a string that has lowercase letters and numbers. Your task is to compare the number groupings and return the largest number. Numbers will not have leading zeros.

For example, solve("gh12cdy695m1") = 695, because this is the largest of all number groupings.

The solution in Python code

Option 1:

import re
def solve(s):
    return max(map(int,re.findall(r"(\d+)", s)))

Option 2:

def solve(s):
    return max(map(int,"".join(" " if x.isalpha() else x for x in s).split()))

Option 3:

def solve(s):
    i, maxn, L = 0, 0, len(s)
    numStart = False
    while i < L:
        if s[i].isdigit():
            j = i+1
            while j<L and s[j].isdigit():
                j += 1
            if int(s[i:j]) > maxn:
                maxn = int(s[i:j])
            i = j+1
        else:
            i += 1
    return maxn

Test cases to validate our solution

test.it("Basic tests")
test.assert_equals(solve('gh12cdy695m1'),695)
test.assert_equals(solve('2ti9iei7qhr5'),9)
test.assert_equals(solve('vih61w8oohj5'),61)
test.assert_equals(solve('f7g42g16hcu5'),42)
test.assert_equals(solve('lu1j8qbbb85'),85)
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags