Skip to main content
2 of 3
added 1 characters in body
Confusion
  • 204
  • 1
  • 5

Instead of taking three elements at a time and comparing them to every other three elements, which takes O(n2) comparisons, you can use the following, which only requires traversing the array once:

from collections import defaultdict

counts = defaultdict(int)
for i in xrange(len(string) - 2):
    counts[tuple(string[i:i+3])] += 1

Using this answer about a Python equivalent to Ruby's each_cons, you can make this even nicer, though I don't know about the performance.

As the array contains characters, you may as well call it a string.

Confusion
  • 204
  • 1
  • 5