Answer to Question #345380 in Python for Mukesh

Question #345380

Python Program


Write a program to print the following, Given a word W and pattern P, you need to check whether the pattern matches the given word.The word will only contain letters(can be Uppercase and Lowercase). The pattern can contain letters, ? and *.


? : Can be matched with any single letter.

* : Can be matched with any sequence of letters (including an empty sequence).


If the pattern matches with the given word, print True else False.


Sample Input1

3

Hello *l?

Hell He?ll

Hell ?*

Sample Output1

True

False

True


Sample Input1

3

Hello Hell*

Hell He*ll

Hell hell*

Sample Output1

True

True

False


1
Expert's answer
2022-05-27T13:35:22-0400
def isMatching(w, p):
    if len(w)<len(p):
        return False
    if len(p) == 0:
        if len(w)==0:
            return True
        return False


    if (w[0]==p[0] or p[0]=='?'):
        return isMatching(w[1:], p[1:])     # isMatching(substring)
    if (p[0]=='*'):
        if(p[1:]==""):                      # in case * is the last character
            return True
        if(p[1:]=="*"):                     # in case of " ** "
            return isMatching(w[1:],p[1:])
    
        occurencies = [i for i in range(1,len(w)) if w[i]==p[1:2]]  #indexes of the next symbol
        return any([isMatching(w[i:], p[1:]) for i in occurencies])
    return False


print("Enter amount of words to check: ")
n = int(input())
answers = []
for i in range(n):
    print("Enter a word-pattern pair (Example: qweqwe q*):")
    word, pattern = [x for x in input().split()]
    answers.append(isMatching(word, pattern))
[print(i) for i in answers]

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS