Search code examples
pythonstringpython-itertools

How to search through a string to see if i can spell a word


For instance I have

x = "dsjcosnag"
y = "dog"

print(checkYinX(y,x))
>>true

So I think I would need to use a while loop as a counter for each of the letter in y, and then I can use itetools to cycle through each of x, each cycle It would check to see if x == y, if it is it would remove it then check the next letter in o.

Is there a more simple way to do this?


Solution

  • Use collections.Counter() to convert x and y to multi-sets, then subtract to see if all of y's letters can be found in x:

    from collections import Counter
    
    def checkYinX(y, x):
        return not (Counter(y) - Counter(x))
    

    Subtracting multi-sets removes characters when their count falls to 0. If this results in an empty multi-set, it becomes False in a boolean context, like all 'empty' python types. not turns that into True if that is the case.

    Demo:

    >>> x = "dsjcosnag"
    >>> y = "dog"
    >>> print(checkYinX(y,x))
    True
    >>> print(checkYinX('cat',x))
    False