- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python – Test for Word construction from character list
When it is required to test for word construction from character list, the ‘all’ operator and the ‘count’ method is used.
Below is a demonstration of the same −
Example
my_list = ['p', 'p', 'y', 't', 'h', 'p', 'p', 'y', 'n', 'y', 'y', 't'] print("The list is :") print(my_list) key = 'pyt' print("The key is :") print(key) my_result = all(key.count(chr) <= my_list.count(chr) for chr in key) print("The result is :") if(my_result == True): print("Word can be constructed. ") else: print("Word can’t be constructed. ")
Output
The list is : ['p', 'p', 'y', 't', 'h', 'p', 'p', 'y', 'n', 'y', 'y', 't'] The result is : Word can be constructed.
Explanation
A list is defined and is displayed on the console.
The value for a key is defined and displayed on the console.
List iteration is used to access all the characters in the list.
It is then compared with the key to check if the key can be constructed.
The ‘all’ operator is used to ensure that all elements are considered.
This is assigned to a variable.
It is displayed as output on the console.
Advertisements