Python - 从字符列表测试单词构造
给定一个 List 和一个 String,测试该字符串是否可以由列表字符组成。
例子:
Input : test_list = [‘g’, ‘g’, ‘e’, ‘k’, ‘s’, ‘4’, ‘g’, ‘g’, ‘e’, ‘s’, ‘e’, ‘e’, ‘4’, ‘k’], test_str = ‘geeks4geeks’
Output : True
Explanation : String can be made according to character frequencies.
Input : test_list = [‘s’, ‘4’, ‘g’, ‘g’, ‘e’, ‘s’, ‘e’, ‘e’, ‘4’, ‘k’], test_str = ‘geeks4geeks’
Output : False
Explanation : String cannot be made according to character frequencies.
方法 #1:使用all() + count()
在这里,我们测试从字符串中计算的所有字符是否小于列表中每个字符的频率。使用 count() 提取频率。
Python3
# Python3 code to demonstrate working of
# Test for Word construction from character list
# Using all() + count()
# initializing list
test_list = ['g', 'g', 'e', 'k', 's', '4', 'g',
'g', 'e', 's', 'e', 'e', '4', 'k']
# printing original list
print("The original list is : " + str(test_list))
# initializing string
test_str = 'geeks4geeks'
# checking for frequency of chars less than in list
res = all(test_str.count(chr) <= test_list.count(chr) for chr in test_str)
# printing result
print("Is word construction possible ? : " + str(res))
Python3
# Python3 code to demonstrate working of
# Test for Word construction from character list
# Using Counter()
from collections import Counter
# initializing list
test_list = ['g', 'g', 'e', 'k', 's', '4', 'g',
'g', 'e', 's', 'e', 'e', '4', 'k']
# printing original list
print("The original list is : " + str(test_list))
# initializing string
test_str = 'geeks4geeks'
# checking for frequency of chars less than in list
res = not bool(dict(Counter(test_str) - Counter(test_list)))
# printing result
print("Is word construction possible ? : " + str(res))
输出:
The original list is : [‘g’, ‘g’, ‘e’, ‘k’, ‘s’, ‘4’, ‘g’, ‘g’, ‘e’, ‘s’, ‘e’, ‘e’, ‘4’, ‘k’]
Is word construction possible ? : True
方法 #2:使用 Counter()
在这里,我们使用 Counter() 计算频率,然后从列表字符中减去单词。在空列表的情况下,意味着不可能形成一个词。
蟒蛇3
# Python3 code to demonstrate working of
# Test for Word construction from character list
# Using Counter()
from collections import Counter
# initializing list
test_list = ['g', 'g', 'e', 'k', 's', '4', 'g',
'g', 'e', 's', 'e', 'e', '4', 'k']
# printing original list
print("The original list is : " + str(test_list))
# initializing string
test_str = 'geeks4geeks'
# checking for frequency of chars less than in list
res = not bool(dict(Counter(test_str) - Counter(test_list)))
# printing result
print("Is word construction possible ? : " + str(res))
输出:
The original list is : [‘g’, ‘g’, ‘e’, ‘k’, ‘s’, ‘4’, ‘g’, ‘g’, ‘e’, ‘s’, ‘e’, ‘e’, ‘4’, ‘k’]
Is word construction possible ? : True