-1

How can I approach this problem?

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 Input2

3

Hello Hell*

Hell He*ll

Hell hell*

Sample Output2

True

True

False

def get(b):
    lis=""
    char=""
    m,k=b
    for i in k:
        if i in m:
            lis+=i
        else:
            if (i=="*") or (i=="?"):
                char+=i


    if lis in m:
        return True
    elif lis.startswith("*") and lis in m:
        return True
    elif len(lis)==0 and char in ("*","?"):
        return True
    
n=int(input())
for i in range(n):
    b=input().split()
    res=get(b) 
    print(res)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65

1 Answers1

-1

Define a function letter_matches(needle, haystack) which looks for needle in haystack. If needle is a single letter or ? it will consider the next letter of haystack.

Controlling iteration elsewhere

In this case haystack is only ever a single letter, and the * case is handled separately.

Then you have a function word_matches which goes through haystack and builds up a 'matched' pattern. In this case you just need the length, so you can increment a counter if you prefer. When you hit '*' in word_matches you shift matched letters into 'matched' (or increment the counter) until letter_matches matches again. If letter_matches fails before the end of the word, shift the entire sequence up to this point into 'matched', rewind the pattern and try again. A match occurs when you exhaust both pattern and word.

Controlling iteration from letter_matches

Instinctively there's also a reduceable solution to this which returns the unmatched part. One option would be to have letter_matches take two needles: current and next. Then it would return an iterable of all possible chunks from least to most greedy. Branches which had leftovers or terminated too soon would be dropped. Whilst an interesting exercise in functional programming, personally I'd write the first version.

Tests!

Regardless of how you write it, first write a comprehensive test suite. If you've never written tests, spend ten minutes on the pytest tutorial. It will change your life :D

2e0byo
  • 5,305
  • 1
  • 6
  • 26