mail@pastecode.io avatar
a month ago
1.7 kB

String Challenge:

Have the function StringChallenge(str) read str which will contain two strings separated by a space. The first string will consist of the following sets of characters: +, *, $, and {N} which is optional. The plus (+) character represents a single alphabetic character, the ($) character represents a number between 1-9, and the asterisk (*) represents a sequence of the same character of length 3 unless it is followed by {N} which represents how many characters should appear in the sequence where N will be at least 1. Your goal is to determine if the second string exactly matches the pattern of the first string in the input.

For example: if str is "++*{5} jtggggg" then the second string in this case does match the pattern, so your program should return the string true. If the second string does not match the pattern your program should return the string false.
Input: "+++++* abcdehhhhhh"
Output: false
Input: "$**+*{2} 9mmmrrrkbb"
Output: true

def StringChallenge(str):
    s = str.split(" ")
    pattern, word = s[0], s[1]
    regex = ""
    for i, c in enumerate(pattern):
        if c == '+':
            regex += "[a-z]"
        elif c == '$':
            regex += "[1-9]"
        elif c == '*':
            if i+1 < len(pattern) and pattern[i+1] == '{':
                regex += ".{" + pattern[i+2] + "}"
                # i += 2  # Skip '{num}' optional
                regex += ".{3}"
    return bool(re.fullmatch(regex, word))

Input = "+++++* abcdehhhhhh" 
print("Input: ", Input)
print("Output: ", StringChallenge(Input))
Input = "$**+*{2} 9mmmrrrkbb"
print("Input: ", Input)
print("Output: ", StringChallenge(Input))
Leave a Comment