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 input 1
3
Hello Helll*
Hell He*ll
Hell hell*
Sample output 1
True
True
False
Sample Input 2
3
Hello *l?
Hell He?ll
Hell ?*
Sample Output 2
True
False
True
def check_equality(w, p):
if len(w) != len(p):
return False
eq = True
for letter in range(len(p)):
if p[letter] != '?' and p[letter] != w[letter]:
eq = False
return eq
count = int(input())
ans = []
for _ in range(count):
word, pattern = input().split()
word_good = True
pattern_parts = pattern.split('*')
pattern_parts = list(filter(bool, pattern_parts))
part_one = pattern_parts[0]
part_last = pattern_parts[-1]
if not (
pattern[0] == '*' or
check_equality(word[:len(part_one)], part_one)
) or not (
pattern[-1] == '*' or
check_equality(word[-len(part_last):], part_last)
):
ans.append(False)
continue
for part in pattern_parts:
part_exist_in_word = False
for i in range(len(word)):
if part[0] == '?' or word[i] == part[0]:
if check_equality(word[i:i + len(part)], part):
part_exist_in_word = True
word = word[i + len(part):]
break
if part_exist_in_word:
continue
else:
word_good = False
break
ans.append(word_good)
[print(i) for i in ans]
Comments
Leave a comment