Efficiently find whether a string contains a group of characters (like substring but ignoring order)?

algorithm, python, string

Solution

You could use `collections.Counter`:

from collections import Counter

substring_counts = Counter(substring)
text_counts = Counter(text)

if all(text_counts[letter] >= count for letter, count in substring_counts.items()):
    # All the letters in `substring` are in `count`

Problem

What's the most efficient way to find whether a group of characters, arranged in a string, exists in a string in Python? For example, if I have `string="hello world"`, and sub-string `"roll"`, the function would return true because all 4 letters in `"roll"` exist in `"hello world"`. There's the obvious brute-force methodology, but I was wondering if there's an efficient Python specific way to achieve this. EDIT: letters count is important. So for example `rollll` isn't included in `hello world` (only three l's).

Original source