Test for Word Construction from Character List in Python



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

 Live Demo

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.

Updated on: 2021-09-04T11:18:00+05:30

174 Views

Kickstart Your Career

Get certified by completing the course

Get Started