Zed
Zed

Reputation: 379

Match characters of a string

If I call matcher.match('bad') it should return a list of all permutations of 'bad' which exist in a provided list. In this example, output will be ['abd']. So far this is what i have tried but I can't seem to match this pattern.

class Matcher():
    def __init__(self, string_list):
        self.string_list = string_list

    def match(self, string_match):
        matched_list = [string for string in string_list if string_match in string]
        return matched_list

string_list = ['abd', 'abdd', 'fret', 'gilk', 'lokm']
matcher = Matcher(string_list)
print(matcher.match('abd'))

Upvotes: 1

Views: 65

Answers (2)

RoadRunner
RoadRunner

Reputation: 26315

You could always use collections.Counter() for this:

from collections import Counter

string_list = ['abd', 'abdd', 'fret', 'gilk', 'lokm']

my_str = 'bad'

print([x for x in string_list if Counter(my_str) == Counter(x)])
# ['abd']

Upvotes: 0

jpp
jpp

Reputation: 164673

This is an O(n log n) solution:

string_list = ['abd', 'abdd', 'fret', 'gilk', 'lokm']

my_str = 'bad'

[x for x in string_list if sorted(my_str) == sorted(x)]  # ['abd']

Upvotes: 3

Related Questions