TypeError problem in for statement with range

Viewed 27
## Shell Sort
def ShellSort(list):
    distance = len(list) // 2
    while distance > 0:
        for i in range(distance, len(list)):
            temp = list[i]
            j = i
            while j >= distance and list[j - distance] > temp:
                list[j] = list[j - distance]
                j = j - distance
            list[j] = temp
        distance = distance / 2
    return list

Above is the code for 'Shell Sort' I typed after reading the algorithm book. But if I try to run it, Error occurs on 'for' statement that 'float' object cannot be interpreted as an integer. distance and len(list) are both int type, but I can't find what is the problem.

1 Answers

/ means "true division", the result is a float. If you want to divide by 2, rounding down to keep distance a true int, use //, which is "floor division". You can save yourself some characters by using //=, changing:

distance = distance / 2

to:

distance //= 2

which will keep distance and int (so it remains a compatible argument to range).

Side-note: Don't name variables list (or any other built-in name); this will bite you when you eventually need to use the list constructor in your code.

Related