Word Pattern Finder
Word Pattern Finder
Python problem for intermediates
Write a Python program to find patterns in words. The input of the program will be the following list of words:
‘ballooned’,’inheritance’ ,’combination’,’despite’,’pommee’ ,’rainfall’,’inches’, ‘seek’,’highest’,’trustworthiness’,
‘caribbean’, ‘experience’,’coffee’, ‘spike’,’greenness’,’wheelless’,’unneeded’,’writers’,’content’,’showcase’,
‘accessily’,’successfully’,’authenticity’,’several’, ‘introductory’,’programming’,’classes’,’occurrence’,’checkers’,
‘board’
The program should check if any of the words in the list match the following patterns:
1) Pattern AABB: This pattern occurs when a word has two letters followed by two identical letters. For example, the word “balloon” matches this pattern.
2) Pattern ABBA: This pattern occurs when a word has a sequence of a letter, followed by two identical letters, and then the same first letter again.
Steps
- Define Patterns:
- Define the patterns XXYY and XYYX as regular expressions to match the given criteria.
- Iterate Through the Words:
- Iterate through each word in the list.
- Check for Patterns:
- Use regular expressions to check if the word matches the defined patterns.
- Display Results:
- Print the words that match each pattern.
Expected output
Pattern AABB found in: pommee Pattern AABB found in: coffee Pattern AABB found in: greenness Pattern ABBA found in: greenness Pattern AABB found in: wheelless Pattern ABBA found in: wheelless Pattern AABB found in: unneeded Pattern AABB found in: ballooned
Solution
import re
# Define the list of words
words = ['BALLOONED','inheritance' ,'combination','despite','pommee' ,'rainfall','inches', 'seek','highest','trustworthiness','caribbean', 'experience','coffee', 'spike','greenness','wheelless','unneeded','writers','content','showcase',
'accessily','successfully','authenticity','several', 'introductory','programming','classes','occurrence','checkers', 'board']
# Define the patterns as regular expressions
pattern_XXYY = r'(\w)\1(\w)\2'
pattern_XYYX = r'(\w)(\w)\2\1'
# Check for patterns in words
for word in words:
if re.search(pattern_XXYY, word):
print(f"Pattern XXYY found in: {word}")
if re.search(pattern_XYYX, word):
print(f"Pattern XYYX found in: {word}")
