An older post had this code in it:
def hamming(num, dist):
if dist == 0:
return num
else:
outputlist = list()
for item in range(len(num)):
if len(num[item:]) > dist - 1:
if num[item] == "0":
restoflist = hamming(num[item + 1:], dist - 1)
outputlist.append(num[:item] + "1" + str(restoflist))
else:
restoflist = hamming(num[item + 1:], dist - 1)
outputlist.append(num[:item] + "0" + str(restoflist))
return outputlist
What is the reasoning behind if len(num[item:]) > dist - 1
?
The test makes sure that the sliced end of num
is long enough to have a distance of dist-1
from the current string. If not, there's no point in recursing. Another way of writing that test (which would be a bit more efficient) is len(num)-item >= dist
.
But really, the check should be dropped and the for
loop's bounds changed instead:
for item in range(len(num) - dist + 1):
if num[item] == "0":
# ...