Write a python program-
Given two lists with words and characters, print all valid words in the words array that are possible using characters from the character array.
Input : words=["go","bat","me","eat","goal","boy", "run"]
characters = ['e','o','b', 'a','m','g', 'l']
Output :
go, me, goal.
Answers
Required Answer:-
Question:
- Given two lists with words and characters, print all valid words that are possible using the characters from the character array. Write a python program for this question.
Solution:
Here comes the program.
n=int(input("How many words? "))
print("Enter them...")
words=[]
for i in range(n):
words.append(input("Enter: ").lower())
n=int(input("How many characters? "))
print("Enter....")
characters=[]
for i in range(n):
characters.append(input("Enter: ").lower())
p=[]
for x in words:
y=True
for j in range(0,len(x)):
if x[j] in characters:
y=True
else:
y=False
break
if y==True:
p.append(x)
print("Given list: ",words)
print("Given characters: ",characters)
print("Words possible are as follows..")
print(*p,sep=",")
Explanation:
- We will take the characters and words as input. Now, taking each word, we will check if all the characters in each word is present in that character array or not. If present, we will append the word in another array. At last, we will display the result.
Output is attached.
Program:
words = input("Enter the words - ").lower( ).split( )
characters = input("Enter the characters - ").lower( ).split( )
def characters_present(word):
for letter in word:
if letter not in characters:
return False
return True
possible_words = [ ]
for word in words:
if characters_present(word):
possible_words.append(word)
print("Possible words - ", end="")
print(*possible_words, sep=", ")
Algorithm:
- Accepting the list of words and characters.
- Checking all entered words if all their letters are present in the characters list.
- Appending all acceptable words into a list.
- Printing the list to display all the possible words.