Created
August 7, 2018 02:18
-
-
Save clintval/9c13e0b11116364e7f3add3ad0e49dc0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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