Skip to content

Instantly share code, notes, and snippets.

@clintval
Created August 7, 2018 02:18
Show Gist options
  • Save clintval/9c13e0b11116364e7f3add3ad0e49dc0 to your computer and use it in GitHub Desktop.
Save clintval/9c13e0b11116364e7f3add3ad0e49dc0 to your computer and use it in GitHub Desktop.
from itertools import combinations, product
def hamming_circle(word, n, alphabet):
"""Create all words of hamming distance `n` in a given alphabet from a
target word.
Examples
---
>>> sorted(hamming_circle('abc', 0, 'abc'))
['abc']
>>> sorted(hamming_circle('abc', 1, 'abc'))
['aac', 'aba', 'abb', 'acc', 'bbc', 'cbc']
>>> sorted(hamming_circle('aaa', 2, 'ab'))
['abb', 'bab', 'bba']
"""
for positions in combinations(range(len(word)), n):
for replacements in product(range(len(alphabet)), repeat=n):
skip = False
cousin = list(word)
for position, replacement in zip(positions, replacements):
if cousin[position] == alphabet[replacement]:
skip = True
else:
cousin[position] = alphabet[replacement]
if not skip:
yield ''.join(cousin)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment