Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to check if a string can be created with a list of characters in python

Tags:

python

I need to check if a string can be created with a list of characters and return True or False.

I am using different solutions with list.count or collections.Counter.

I am also using this solution which I dont need to read through the list of characters:

def check(message, characters):
    try:
        [list(characters).remove(m) for m in message]
        return True
    except:
        return False

Is there a fastest way? for a very very very big list of characters. Counter and list count seems slower. Dont know if there is a fast pythonic way to do this.

Example:

message = "hello"
characters = "hheellooasdadsfgfdgfdhgfdlkgkfd"

check(message, characters) # this should return True or False
# characters can be a veeeeery long string

Duplicates matter so for example characters = "hheloo" would not work for message = "hello"

like image 405
lapinkoira Avatar asked Jan 22 '26 12:01

lapinkoira


1 Answers

You could use collections.Counter(). Just build two counters and use the subtract() method to check if there're any negative counts:

>>> c1 = Counter(characters)
>>> c2 = Counter(message)
>>> c1.subtract(c2)
>>> all(v >= 0 for v in c1.values())
False

This should work in linear time.

like image 186
Eugene Yarmash Avatar answered Jan 24 '26 02:01

Eugene Yarmash