AndTuf AndTuf - 1 month ago 12
Python Question

How to optimize this code in python

I need to optimize this code, that basically checks if every character of string

is contained in
, taking in consideration doubles.

s1, s2 = list(s1), list(s2)
for s in s2:
if s in s1:
return False
return True

I did some research on
, iterators and generators, and I'm sure in one or more of these there is a solution, but right now I'm pretty confused and frustrated (I'm very new to python, just a couple weeks), so maybe you can help me understand what's the best strategy in this case. Thanks!

Answer Source

A solution using Counter that will handle duplicated characters correctly:

from collections import Counter
c1 = Counter(s1)
c2 = Counter(s2)
return all(c2[c]>=c1[c] for c in c1)