Search code examples
pythonfunctioncounter

Function to see if i can generate phrase from characters string


I am trying to write a function that checks if I can generate the required word/phrase using the characters provided. The phrase created can contain any characters including special characters, capital letters, numbers, and spaces.

I can generate the phrase if the frequency of unique characters in the characters string is equal or greater than the frequency in the phrase.

What I tried to do was use a counter and then compare the dictionaries that it produced but not sure how to find if the characters in the character string are more in frequency than in the phrase.

This is my code:

from collections import Counter

def generate_phrase(characters, phrase):
  new_characters = characters.lower()
  new_phrase = phrase.lower()
  a = Counter(new_characters)
  b = Counter(new_phrase)
  if a == b:
    return True 
  else:
    return False  

This example should produce false, as there are less characters in the character string than the phrase

characters = "cbacba"
phrase = "aabbccc"

generate_phrase(characters, phrase)

Ouput:
False

This example should produce True as although it has other letters in it, that are not in the phrase. It does contain all characters of the phrase and the right frequency of them.

characters = "Magiciansktb!"
phrase = "m!aagsnici"

generate_phrase(characters, phrase)

Ideal Ouput:
True

My current code output:
False

Solution

  • Alternatively, you can try this code to see if it helps you:

    It tries to handle some edge cases here, if errors caught earlier, and it bails out right away, will not go further process. Just make a note of it.

    
    def generate_phrase(letters: str, phrase: str) -> bool:
        phrase_cnt = Counter(phrase.lower())
        chars_cnt  = Counter(letters.lower())
    
        if not phrase_cnt and not chars_cnt:      # both are empty?
            return True
            
        #if not letters:  return False
            
        if len(phrase) >  len(letters):       # not enought letters?
            return False
    
    
        for ch, cnt in phrase_cnt.items():
         
            if ch in chars_cnt and cnt <= chars_cnt.get(ch):
                continue
            else:
                return False 
            
        return True
    
    
    if __name__ == '__main__':
        characters = "cbacba"
        phrase = "aabbccc"
    
        print(generate_phrase(characters, phrase))          # False
    
        print(generate_phrase('footeatips', 'tattoo'))      # False
    
        print(generate_phrase('gooseteatipstim', 'tattoo'))  # True
    
        characters2 = "Magiciansktb!"
        phrase2 = "m!aagsnici"
        print(generate_phrase(characters2, phrase2))   # True