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
Python – Test for Word construction from character list
When it is required to test if a word can be constructed from a character list, the all() function and the count() method are used together. This approach checks if each character in the target word appears enough times in the available character list.
Syntax
all(word.count(char) <= char_list.count(char) for char in word)
Example
Here's how to check if the word "pyt" can be constructed from a list of available characters ?
char_list = ['p', 'p', 'y', 't', 'h', 'p', 'p', 'y', 'n', 'y', 'y', 't']
print("The character list is:")
print(char_list)
word = 'pyt'
print("The word to construct is:")
print(word)
result = all(word.count(char) <= char_list.count(char) for char in word)
print("The result is:")
if result:
print("Word can be constructed.")
else:
print("Word can't be constructed.")
The character list is: ['p', 'p', 'y', 't', 'h', 'p', 'p', 'y', 'n', 'y', 'y', 't'] The word to construct is: pyt The result is: Word can be constructed.
How It Works
The solution uses a generator expression inside all() that:
- Iterates through each character in the target word
- Counts how many times each character appears in the word using
word.count(char) - Counts how many times the same character appears in the available list using
char_list.count(char) - Checks if the required count is less than or equal to the available count
- Returns
Trueonly if all characters pass this test
Testing with Insufficient Characters
Let's test with a word that cannot be constructed ?
char_list = ['p', 'y', 't']
word = 'python'
result = all(word.count(char) <= char_list.count(char) for char in word)
print(f"Can construct '{word}' from {char_list}: {result}")
# Let's see why it fails
for char in set(word):
needed = word.count(char)
available = char_list.count(char)
print(f"Character '{char}': need {needed}, have {available}")
Can construct 'python' from ['p', 'y', 't']: False Character 'p': need 1, have 1 Character 'y': need 1, have 1 Character 't': need 1, have 1 Character 'h': need 1, have 0 Character 'o': need 1, have 0 Character 'n': need 1, have 0
Conclusion
Use all() with count() to verify word construction by ensuring each character appears enough times in the available character list. This method efficiently handles duplicate characters and returns True only when the word can be fully constructed.
