Possible Words using given characters in Python
Possible Words using given characters in Python
Given a dictionary and a character array, print all valid words that are possible using characters from the array.
Note: Repetitions of characters is not allowed.
Examples:
Note: Repetitions of characters is not allowed.
Examples:
Input : Dict = ["go","bat","me","by","goal","boy", "run","be"] arr = ['e','o','b', 'a','m','g', 'l','y'] Output : go, me, goal,boy.
This problem has existing solution please refer Print all valid words that are possible using Characters of Array link. We will this problem in python very quickly using Dictionary Data Structure. Approach is very simple :
def charCount(word):
dict = {}
for i in word:
dict[i] = dict.get(i, 0) + 1
return dict
def possible_words(lwords, charSet):
for word in lwords:
flag = 1
chars = charCount(word)
for key in chars:
if key not in charSet:
flag = 0
else:
if charSet.count(key) != chars[key]:
flag = 0
if flag == 1:
print(word)
if __name__ == "__main__":
input = ['go', 'bat', 'me', 'eat', 'goal', 'boy', 'run','be']
charSet = ['e', 'o', 'b', 'a', 'm', 'g', 'l','y']
possible_words(input, charSet)
Comments
Post a Comment