0

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 ?

Community
  • 1
  • 1
user3290553
  • 87
  • 1
  • 2
  • 9

2 Answers2

2

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":
        # ...
Blckknght
  • 100,903
  • 11
  • 120
  • 169
0

num[item:] will return a list starting at the index of item going to the end. So the length of that will get the elements until the end of the list.

dist -1 is the equivalent of saying >= dist.

Ian Leaman
  • 135
  • 7