Open In App

Possible Words using given characters in Python

Last Updated : 10 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Input : Dict = ["go","bat","me","eat","goal","boy", "run"]
        arr = ['e','o','b', 'a','m','g', 'l']
Output : go, me, goal. 

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 :

  1. Traverse list of given strings one by one and convert them into dictionary using Counter(input) method of collections module.
  2. Check if all keys of any string lies within given set of characters that means this word is possible to create.

Python




# Function to print words which can be created
# using given set of characters
 
 
 
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 = ['goo', 'bat', 'me', 'eat', 'goal', 'boy', 'run']
    charSet = ['e', 'o', 'b', 'a', 'm', 'g', 'l']
    possible_words(input, charSet)


Output:

go 
me
goal

Time complexity: O(n^2)

Space complexity: O(n)

https://www.youtube.com/watch?v=9pzQKdBhj04

Recursive approach:

First, we define a function find_words(dictionary, characters, word=”) that takes in three arguments:

  1. dictionary: a list of strings representing the valid words that can be formed from the given characters
  2. characters: a list of characters that can be used to form the words
  3. word: a string representing the current combination of characters being checked (initially empty)

The function has two cases:

  1. The base case: if word is in the dictionary, it means that we have found a valid word, so we print it.
  2. The recursive case: for each character in the characters list, we create a copy of the characters list called new_characters and remove the current character from it. We then call find_words again with the new_characters list and the current word appended with the current character. This will recursively check all possible combinations of characters to see if they form a word in the dictionary.

Finally, we have an example of how to use the find_words function, where we define the dictionary and characters lists and call find_words with those lists as arguments.

Python3




def find_words(dictionary, characters, word=''):
    # base case: if the word is in the dictionary, print it
    if word in dictionary:
        print(word)
     
    # recursive case: for each character in the characters list, make a new list of characters
    # with that character removed, and call find_words with the new list of characters and the
    # current word appended with the current character
    for char in characters:
        new_characters = characters.copy()
        new_characters.remove(char)
        find_words(dictionary, new_characters, word + char)
 
# example usage
dictionary = ["go","bat","me","eat","goal","boy", "run"]
characters = ['e','o','b', 'a','m','g', 'l']
find_words(dictionary, characters)


Output

me
go
goal

The time complexity of the recursive approach to solving this problem is dependent on the number of valid words that can be formed from the given characters and the length of those words.

In the worst case, the time complexity is O(n^m), where n is the number of characters in the characters list and m is the maximum length of the words in the dictionary. This is because the recursive function generates and checks all possible combinations of characters of length up to m, and there are n choices for each character in the combination.

For example, if the dictionary contains all words of length m that can be formed from the characters list, and the characters list has n elements, then the function will generate and check a total of n^m combinations.

On the other hand, if the dictionary is small and the words in the dictionary are short, the time complexity will be much lower. For example, if the dictionary contains only one word of length 1, the time complexity will be O(n).

It’s worth noting that the time complexity of the recursive approach may not be as efficient as the approach provided in the original article, which only needs to check each word in the dictionary individually and does not generate and check all possible combinations of characters.

Approach#3:  Using set and subsets

This approach takes a list of words (Dict) and a list of characters (arr) as input. It first creates a set of characters from the input list. Then, it iterates over each word in the dictionary, and checks if the set of characters in that word is a subset of the input set of characters. If it is, then the word is added to the result list. Finally, the function returns the list of words that can be formed using the input characters.

Algorithm

1. Convert the array into a set.
2. Initialize an empty list result to store the possible words.
3. Loop through each word in the given dictionary Dict.
4. Convert the word into a set.
If the set of the word is a subset of the given set arr, append the word to the result list.
5. Return the result list.

Python3




def possible_words(Dict, arr):
    arr_set = set(arr)
    result = []
    for word in Dict:
        if set(word).issubset(arr_set):
            result.append(word)
    return result
 
 
Dict = ["go", "bat", "me", "eat", "goal", "boy", "run"]
arr = ['e', 'o', 'b', 'a', 'm', 'g', 'l']
print(possible_words(Dict, arr))


Output

['go', 'me', 'goal']

Time Complexity: O(n*m), where n is the length of the dictionary Dict and m is the length of the longest word in the dictionary. In the worst case, we may have to check all the letters in the longest word in the dictionary against the letters in the given array arr.

Space Complexity: O(m), where m is the length of the longest word in the dictionary. We are using an extra set to store the letters of each word in the dictionary.



Similar Reads

Print all valid words from given dictionary that are possible using Characters of given Array
Given a dictionary of strings dict[] and a character array arr[]. Print all valid words of the dictionary that are possible using characters from the given character array.Examples: Input: dict - ["go", "bat", "me", "eat", "goal", boy", "run"] arr[] = ['e', 'o', 'b', 'a', 'm', 'g', 'l']Output: "go", "me", "goal".Explanation: Only all the characters
5 min read
Print all valid words that are possible using Characters of Array
Given a dictionary and a character array, print all valid words that are possible using characters from the array. Examples: Input : Dict - {"go","bat","me","eat","goal", "boy", "run"} arr[] = {'e','o','b', 'a','m','g', 'l'} Output : go, me, goal. Asked In : Microsoft Interview The idea is to use Trie data structure to store dictionary, then search
13 min read
Boggle (Find all possible words in a board of characters) | Set 1
Given a dictionary, a method to do lookup in dictionary and a M x N board where every cell has one character. Find all possible words that can be formed by a sequence of adjacent characters. Note that we can move to any of 8 adjacent characters, but a word should not have multiple instances of same cell. Example:  Input: dictionary[] = {"GEEKS", "F
15+ min read
Check if the given string of words can be formed from words present in the dictionary
Given a string array of M words and a dictionary of N words. The task is to check if the given string of words can be formed from words present in the dictionary. Examples: dict[] = { find, a, geeks, all, for, on, geeks, answers, inter } Input: str[] = { "find", "all", "answers", "on", "geeks", "for", "geeks" }; Output: YES all words of str[] are p
15+ min read
Find all words from String present after given N words
Given a string S and a list lis[] of N number of words, the task is to find every possible (N+1)th word from string S such that the 'second' word comes immediately after the 'first' word, the 'third' word comes immediately after the 'second' word, the 'fourth' word comes immediately after the 'third' word and so on. Examples: Input: S = “Siddhesh i
11 min read
Python - Compute the frequency of words after removing stop words and stemming
In this article we are going to tokenize sentence, paragraph, and webpage contents using the NLTK toolkit in the python environment then we will remove stop words and apply stemming on the contents of sentences, paragraphs, and webpage. Finally, we will Compute the frequency of words after removing stop words and stemming. Modules Needed bs4: Beaut
8 min read
How to Remove repetitive characters from words of the given Pandas DataFrame using Regex?
Prerequisite: Regular Expression in Python In this article, we will see how to remove continuously repeating characters from the words of the given column of the given Pandas Dataframe using Regex. Here, we are actually looking for continuously occurring repetitively coming characters for that we have created a pattern that contains this regular ex
2 min read
Maximize cost of forming a set of words using given set of characters
Given an array arr[] consisting of N strings, an array letter[] consisting of M lowercase characters, and an array score[] such that score[i] is the cost of ith English alphabets, the task is to find the maximum cost of any valid set of words formed by using the given letters such that each letter can be used at most once and each word arr[i] can b
15+ min read
Python | Words extraction from set of characters using dictionary
Given the words, the task is to extract different words from a set of characters using the defined dictionary. Approach: Python in its language defines an inbuilt module enchant which handles certain operations related to words. In the approach mentioned, following methods are used. check() : It checks if a string is a word or not and returns true
3 min read
Count words that appear exactly two times in an array of words
Given an array of n words. Some words are repeated twice, we need to count such words. Examples: Input : s[] = {"hate", "love", "peace", "love", "peace", "hate", "love", "peace", "love", "peace"}; Output : 1 There is only one word "hate" that appears twice Input : s[] = {"Om", "Om", "Shankar", "Tripathi", "Tom", "Jerry", "Jerry"}; Output : 2 There
6 min read