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

Discussão em 'Python' iniciado por Stack, Maio 3, 2025.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página