DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

HHMathewChan
HHMathewChan

Posted on • Originally published at rebirthwithcode.tech

Python Exercise 20:Find the pattern

Question

  • Given a dictionary containing up to six phrases,
    • return a list containing the matching phrases according to theΒ given string (p).
  • Ignore any digit that is placed after or before the given string.
  • Whether the first letter is capitalized or not,
    • if all letters of the word match theΒ given string (p), it is valid.
  • If it does not match theΒ given string (p)Β then None.

Example

  • example 1
find_pattern({
  "Phrase1": "COVID-19 is no good",
  "Phrase2": "COVID-18 is no good",
  "Phrase3": "COVID-17 is no good"
}, "COVID-19")

➞ ["Phrase1 = COVID-19", "Phrase2 = None", "Phrase3 = None"]
Enter fullscreen mode Exit fullscreen mode
  • example 2
find_pattern({
  "Phrase1": "Edabit is great",
  "Phrase2": "Edabit is very great",
  "Phrase3": "Edabit is really great"
}, "really")

➞ ["Phrase1 = None", "Phrase2 = None", "Phrase3 = really"]
Enter fullscreen mode Exit fullscreen mode

My solution

  • algorithm
>>get the value of each Phrase
>>separate the the value into a list by white space 
>>store each separated value into list
  the list name from phase1_list to phase6_list
>>check if the given string (p) appear in the each phrase
  for phrase1 to phrase 6:
      if the given string (p) appear in the phrase value
      add that phrase and value into one string
      add that string to the final list
>>return a final list
Enter fullscreen mode Exit fullscreen mode
  • code
def find_pattern(dictionary: dict, string_p: str) -> list:  
    prefix = "Phrase"  
    counter = 1  
    final_list = []  
    for sentence in dictionary.values():  
        if string_p in sentence:  
            final_list.append(f"{prefix}{counter} = {string_p}")  
        else:  
            final_list.append(f"{prefix}{counter} = None")  
        counter += 1  
    return final_list
Enter fullscreen mode Exit fullscreen mode

Other solution

def find_pattern(dict_, p):
    phrase = {True:p,False:"None"}
    phrases = []
    for key,val in dict_.items():
        phrases.append('{} = {}'.format(key,phrase[p in val]))
    return sorted(phrases)
Enter fullscreen mode Exit fullscreen mode
  • shortest version
def find_pattern(dct, p):
    return sorted("{} = {}".format(d, p if p in dct[d] else None) for d in dct)
Enter fullscreen mode Exit fullscreen mode

Credit

Top comments (0)

🌚 Life is too short to browse without dark mode