Decrease the cost of two lists comparisons
<p>I want to minimize the cost of comparisons of two lists that have some words. In the code below <code>A</code> has 4 words whereas <code>B</code> has 2 words and the cost is <code>O(n^2)</code> that is too bad. While for 100 words it can be time consuming. Can I minimize it somehow?</p>

<pre><code>A= ["helry", "john" , "kat" , "david"]
d="Helry David"
B = d.lower().split()

for x in range(len(A)):
            for i in range(len(B)):
                if A[x] == B[i]:
                    print("Match = " + A[x])
                else:
                    print("No")
</code></pre>

<p>You can do it in <em>O(n)</em> time with sets and testing for <em>membership</em> with <code>in</code>, you still have to iterate over all the names In <code>A</code> but checking if each name is in the setof name is <code>O(1)</code>:</p>

<pre><code>A = ["helry", "john" , "kat" , "david"]
d = "Helry David"
st = set(d.lower().split())

for name in A:
    if name in st:
        print("Match = {}".format(name))
    else:
        print("No match")
</code></pre>

python time-complexity