Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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).

like image 540
Roee Adler Avatar asked Oct 25 '16 03:10

Roee Adler


People also ask

How do you check if a string contains a substring?

You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.

Which function determine if the substring is present in string or not?

find() str. find() method is generally used to get the lowest index at which the string occurs, but also returns -1, if string is not present, hence if any value returns >= 0, string is present, else not present.

How do you find if a string contains a substring in Python?

The in Operator It returns a Boolean (either True or False ). To check if a string contains a substring in Python using the in operator, we simply invoke it on the superstring: fullstring = "StackAbuse" substring = "tack" if substring in fullstring: print("Found!") else: print("Not found!")

How do you check if a string contains a specific character in Python?

Using Python's "in" operator The simplest and fastest way to check whether a string contains a substring or not in Python is the "in" operator . This operator returns true if the string contains the characters, otherwise, it returns false .


1 Answers

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`
like image 148
Blender Avatar answered Sep 29 '22 14:09

Blender