Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Possible Words using given characters in Python
In this article, we'll see how to find possible words that can be formed using a given set of characters. We'll take a list of reference words and a list of available characters, then determine which words can be made from those characters.
The program uses two functions: one to count character frequencies, and another to check if each word can be formed from the available characters.
Example
Here's how to find words that can be formed from given characters:
def count_characters(character):
char_count = {}
for n in character:
char_count[n] = char_count.get(n, 0) + 1
return char_count
def find_possible_words(word_list, available_chars):
for word in word_list:
can_form = True
word_char_count = count_characters(word)
available_char_count = count_characters(available_chars)
for char in word_char_count:
if char not in available_char_count:
can_form = False
break
elif available_char_count[char]
The output of the above code is:
fat
tap
day
aim
How It Works
The algorithm works by:
-
Character Counting: The
count_characters()function creates a dictionary with character frequencies - Word Validation: For each word, we check if all required characters are available in sufficient quantities
- Comparison: We compare the character count needed for each word against the available characters
Alternative Approach Using Collections
Here's a more concise version using Python's Counter class:
from collections import Counter
def find_words_with_counter(word_list, available_chars):
available_count = Counter(available_chars)
for word in word_list:
word_count = Counter(word)
if all(available_count[char] >= count for char, count in word_count.items()):
print(word)
# Test data
word_list = ['fat', 'tap', 'day', 'fun', 'man', 'ant', 'bag', 'aim']
available_chars = ['m', 't', 'e', 'd', 'f', 'a', 'p', 'y', 'i']
find_words_with_counter(word_list, available_chars)
fat tap day aim
Conclusion
Both approaches effectively find words that can be formed from available characters by counting character frequencies. The Counter approach is more concise and readable for this type of problem.
