给定2个字符串str和word,您必须找到从该给定字符串中可以生成多少个单词



我正在尝试解决一些问题,尽管逻辑看起来很简单,但我无法构建可能的解决方案。

给定2个字符串str和word,您必须找到从该给定字符串中可以生成多少个单词。

输入:str="这是一个测试字符串";word=";tsit";,输出:2

说明:给定的str中有4个t,4个s,3个i,由此只能使2";tsit";。

输入:str=";这里是HashedIn Technologies";word=";神经元";输出:0

说明:由于str中没有"u",所以不能构成单词"u";神经元";。

我试图使用字典逻辑是递增计数,直到任何字符计数变为零,但我如何将其放入代码中?

def freq(s, word):
s = s.lower()
aux_s = {}
aux_word = {}
for i in s:
aux_s[i] = aux_s.get(i, 0) + 1
for i in word:
aux_word[i] = aux_word.get(i, 0) + 1
count, ans = 0, float('inf')
for i,val in aux_s.items():
if i in aux_word:
pass

由于根据您的示例,情况无关紧要,

str = "This is a test string".lower()
word = "tsit"
ans = len(str)
for i in word:
ans = min(ans, str.count(i)//word.count(i))
print(ans)

我在解决方案中使用了Dictionary,我只是对您使用的逻辑做了一点更改。

import sys
test_str = "This is a test string"
test_str = test_str.lower()
word = "tsit"
res = {} 
word_count = {}
# loop to count frequency of all the characters in word
for keys in word:
if keys != ' ':
word_count[keys] = word_count.get(keys, 0) + 1
# loop to count frequency of all the characters in string
for keys in test_str: 
if keys != ' ':   # if the char is space then ignore it
res[keys] = res.get(keys, 0) + 1  # increment the count of the character if the character already exists
# assigning ans a max value
ans = sys.maxsize

for keys in word_count:
if keys in res:
a = res[keys]    #checking if the key exists in the res or not
else:
ans = 0   # if the char does not exist in the string then ans = 0
break
b = word_count[keys]
n = a//b
if n < ans:   # finding the lowest of the requirement
ans = n   # assigning it to the answer

print(ans)   # print the answer 

最新更新