Reputation: 57
I am trying to solve some questions, even though the logic seems very straight forward, I am not able to construct a possible solution.
Given 2 Strings str and word, you have to find how many words can you make from that given string.
Input : str="This is a test string" word="tsit" , Output : 2
Explanation : there are 4 t's 4 s's 3 i's in the given str, by which you can only make 2 "tsit".
Input: str="Here is HashedIn Technologies" word="neurons" Output : 0
Explanation: since you do not have 'u' in str. thus u can't form word "neurons".
I was trying to use dictionary logic was increment count till any of the character count turns zero but how do i put it into code?
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
Upvotes: 1
Views: 994
Reputation: 23
I have used Dictionary in the Solution , i have just changed a little bit on the logic which you have used.
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
Upvotes: 0
Reputation: 8101
Since case doesn't matter as per your example,
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)
Upvotes: 2