python-3.xstringlist

Check whether one string can be formed by another string in Python


I want to check whether one string can be formed by another string, e.g., in the example below, I want to check how many strings in the list targets can be formed by string chars. Each character in chars can only be used once.

targets = ["cat","bt","hat","tree"], chars = "atach"

My code is as follows:

 ans = 0
 chars_freq = Counter(chars)
 for word in targets:
     word_freq = Counter(word)
     for char in word:
         if word_freq[char] > chars_freq[char]:
             break
     ans += 1
 return ans

For the example the answer should be 2, but mine gets 4. Who can help? Thank you.


Solution

  • break only escapes from the innermost for-loop

    So in your example, after the inner loops end (wether because of the break or not), ans is incremented by one.

    As suggested in the comment, putting the increment into an else block would only execute if the inner loop did not break:

         for char in word:
             if word_freq[char] > chars_freq[char]:
                 break
         else:
             ans += 1
    

    See also this answer