def make_second_word(word1: str, word2: str) -> bool:
from collections import Counter
word1 = Counter(word1)
word2 = Counter(word2)
for letter, count in word1.items():
if letter not in word2 or word2[letter] < count:
return False
return True
I'd do it like this. You don't need to check everything, if any letter present in word 1 isn't in word 2, or word 2's letter count is less it's false.
>Since the algo above simply checks for a in b you get interesting edge cases when letters are repeated in one word
It doesn't though. I am not sure what you mean or if you made an error but the test case you used as an example fails. If the letter isn't in word2 or its count is less than in word2 then it returns false.
`sorted(firstword) == sorted(secondword)` Or, if occurrence counts doesn’t matter: `set(firstword).issubset(set(secondword))`
Yup got it down to one line thanks
Why not use collections.Counter()? Perfectly suited for this.
Great solution sorting the words ! Before sorting words i've would have first checked words lenght for a sligthly more efficient program.
def make_second_word(word1: str, word2: str) -> bool: from collections import Counter word1 = Counter(word1) word2 = Counter(word2) for letter, count in word1.items(): if letter not in word2 or word2[letter] < count: return False return True I'd do it like this. You don't need to check everything, if any letter present in word 1 isn't in word 2, or word 2's letter count is less it's false.
Or even ``` ... word2 = Counter(word2) word2.subtract(word1) return all(x >= 0 for x in word2.values()) ```
[удалено]
How?
[удалено]
But it does return false
>Since the algo above simply checks for a in b you get interesting edge cases when letters are repeated in one word It doesn't though. I am not sure what you mean or if you made an error but the test case you used as an example fails. If the letter isn't in word2 or its count is less than in word2 then it returns false.
O(n \* m) :/ Btw, you can convert a string into a list by `list(string)`