Possible Words using given characters in Python

Given a dictionary and a character array, print all valid words that are possible using characters from the array.

Examples:

Input : Dict = ["go","bat","me","eat","goal","boy", "run"]
        arr = ['e','o','b', 'a','m','g', 'l']
Output : go, me, goal. 



This problem has existing solution please refer Print all valid words that are possible using Characters of Array link. We will this problem in python very quickly using Dictionary Data Structure. Approach is very simple :

  1. Traverse list of given strings one by one and convert them into dictionary using Counter(input) method of collections module.
  2. Check if all keys of any string lies within given set of characters that means this word is possible to create.
filter_none

edit
close

play_arrow

link
brightness_4
code

# Function to print words which can be created
# using given set of characters
  
from collections import Counter
  
def possibleWords(input,charSet):
      
    # traverse words in list one by one
    for word in input:
  
        # convert word into dictionary
        dict = Counter(word)
          
        # now check if all keys of current word 
        # are present in given character set
        flag = 1 
        for key in dict.keys():
            if key not in charSet:
                flag = 0
          
        # if all keys are present ( flag=1 ) 
        # then print the word
        if flag==1:
            print word
  
# Driver program
if __name__ == "__main__":
    input = ['go','bat','me','eat','goal','boy','run']
    charSet = ['e','o','b', 'a','m','g', 'l']
    possibleWords(input,charSet)

chevron_right


Output:

go 
me
goal


My Personal Notes arrow_drop_up

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry Skilled in Big Data technologies, Data Structures, Algorithm, Software Development, App Development, Databases, Python, Java, C, and WordPress

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.