Given a dictionary and a character array, print all valid words that are possible in Python
|In this Python example we will discuss the following problem statement. Given a dictionary of words and a character array, write a function that prints all valid words that are possible using characters from the array. A word is considered valid if it can be formed using only the characters from the array, and if it is present in the dictionary.
Some of the topics which will be helpful for understanding the program implementation better are:
1. Using a for loop
We can iterate through each word in the dictionary and check if it can be formed using only the characters in the char_array
. To check if a word can be formed using the characters in the array, we can convert the word and the array into sets and use the issubset()
method to check if that is the subset of the character array.
Now let’s implement a program for this problem –
def print_valid_words(dictionary, char_array): for word in dictionary: if set(word).issubset(set(char_array)): print(word) dictionary = {'cat', 'dog', 'act', 'god', 'bat'} char_array = ['a', 'c', 't', 'o', 'g', 'd'] print_valid_words(dictionary, char_array)
Output cat god dog act
2. Using list comprehension
This is exactly like the previous example but instead of using a for loop we will use list comprehension to achieve the same.
Now let’s implement a program for this problem –
def print_valid_words(dictionary, char_array): valid_words = [word for word in dictionary if set(word).issubset(set(char_array))] print(valid_words) dictionary = {'cat', 'dog', 'act', 'god', 'bat'} char_array = ['a', 'c', 't', 'o', 'g', 'd'] print_valid_words(dictionary, char_array)
Output ['cat', 'god', 'dog', 'act']
3. Conclusion
In this Python example, we discussed how to print all valid words that can be formed using characters from a given character array, using a dictionary in Python. We explored two methods to solve this problem
Helpful Links
Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.
Also for examples in Python and practice please refer to Python Examples.
Complete code samples are present on Github project.
Recommended Books
An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding
Do not forget to share and Subscribe.
Happy coding!! ?