fork(2) download
def H(s, k):
    if k == 0:
        yield s  # only one n-bit string has Hamming distance 0 from s (itself)
    elif s: # k > 0
        for s_k_minus_one_flipped in H(s[:-1], k - 1):
            yield s_k_minus_one_flipped + flip(s[-1])  # flip last bit
        for s_k_flipped in H(s[:-1], k):
            yield s_k_flipped + s[-1]  # don't flip last bit


def flip(bit):
    assert bit == "0" or bit == "1"
    return "0" if bit == "1" else "1"

import sys
s, k = sys.stdin.read().split()
print(" ".join(H(s, int(k))))
Success #stdin #stdout 0.08s 10840KB
stdin
0000 2
stdout
0011 0101 1001 0110 1010 1100