title: How do I reduce the time complexity of this code snippet in Python?
body: <p>I have a <code>compare</code> function here which compares 2 4-digit numbers (non-repeating digits) and gives <code>x</code> (no. of digits in both <code>n1</code> and <code>n2</code> and in the same position), and <code>y</code> (no. of digits in both <code>n1</code> and <code>n2</code>, but in different positions). What I do is I use a <code>for</code> loop to store the digit as the key of the <code>results</code> dictionary and the corresponding position as the value of the <code>results</code> dictionary. Then, I use another <code>for</code> loop to iterate through the dictionary to give me <code>x</code> and <code>y</code>. Is there any way of reducing the time complexity of this function?</p>
  <pre><code>def compare(n1, n2):
      x, y = 0, 0
      result = {}
      s1, s2 = str(n1), str(n2)
      for i in range(0, 4):
          result[s1[i]] = i 
      for i in range(0, 4):
          if s2[i] in result:
              if result[s2[i]] == i:
                  x += 1
              else:
                  y += 1
  </code></pre>