What\'s the easiest way to check if a string only contains certain specified characters in Python? (Without using RegEx or anything, of course)
Specifically, I have
The question is somewhat ambiguous about re-using letters from the base string. Or if there should or should not be repeats, or missing letters allowed. This solution addresses that with a function including a reuse
parameter:
from collections import Counter
def anagram_filter(data, base, reuse=True):
if reuse: # all characters in objects in data are in base, count ignored
base = set(base)
return [d for d in data if not set(d).difference(base)]
r = []
cb = Counter(base)
for d in data:
for k, v in Counter(d).iteritems():
if (k not in cb.keys()) or (v > cb[k]):
break
else:
r.append(d)
return r
Usage:
>>> anagram_filter(['aba', 'acba', 'caz'], 'abc')
['aba', 'acba']
>>> anagram_filter(['aba', 'acba', 'caz'], 'abc', False)
[]
>>> anagram_filter(['aba', 'cba', 'caz'], 'abc', False)
['cba']