Python程序使用给定字符打印可能的单词
在本教程中,我们将查找带有给定字符的所有可能单词。让我们看一些测试用例,以更好地理解。
Input: words = ["hi", "hello", "bye", "good"] characters = ["h", "i", "b", "y", "e"] Output: hi bye
让我们按照以下步骤实现我们的目标。
算法
1. Initialize the words and characters list.
2. Write a function which returns a dictionary containing a count of each char of the word.
2.1. Initialise an empty dictionary.
2.2. Iterate through the word, and increment char count by one if already present else initialise it with one.
2.3. After the loop return dictionary.
3. Iterate through the words list.
3.1. Initialise a variable flag with 1.
3.2. Find char count with the help of above function and store it in a variable.
3.3. Iterate through the above-returned dictionary.
3.3.1. Check whether the key is in the characters or not.
3.3.1.1. If not present, make the flag to zero.
3.3.2 Else check for the equality count of character in characters and dictionary.
3.3.2.1. If not equal, make a flag to zero.
3.4. If the flag is equal to one.
3.4.1. Print the word.让我们实现以上算法。
示例
## initializing the lists
words = ["hi", "hello", "bye", "good"]
characters = ["h", "i", "b", "y", "e"]
## function which returns dictionary containing char counts
def char_count(word):
## initializing an empty dictionary
char_count = {}
## loop to find the frequency of the chars
for char in word:
## incrementing the char count by one
char_count[char] = char_count.get(char, 0) + 1
## returning dictionary
return char_count
## iterating through the words list
for word in words:
## initializing flag to one
flag = 1
## getting the char count using char_count() function
chars = char_count(word)
## iterating through the chars
for key in chars:
## checking for the presence of key in the characters
if key not in characters:
## updating the flag value to zero
flag = 0
else:
## comparing the count of chars in chars and characters
if characters.count(key) != chars[key]:
## updating the flag value to zero
flag = 0
## checking the flag value
if flag == 1:
print(word)输出结果
如果运行上面的程序,您将得到以下结果。
hi bye
结论
热门推荐
1 训练狗狗工作
4 狗狗定点排便训练
5 狗狗训练吠叫
6 狗狗尿垫训练
7 狗狗训练座
8 狗狗训练攻略
9 狗狗训练记
10 做训练狗狗
11 狗狗训练词
12 狗狗谢谢怎么训练
13 狗狗训练如厕
14 狗狗太凶怎么训练
15 狗狗训练它
16 狗狗克制训练
17 训练基地狗狗
18 怎么样训练狗狗大小硬