TypeError: can not multiply sequence by non-int of type 'float'

1

I'm learning to program in python , but I came across an error while trying to build merge sort using object orientation. When calling the sort() method that belongs to the MergeSort class, the following error is displayed: TypeError: can't multiply sequence by non-int of type 'float' . I'm using Python 3.6.1 .

MERGESORT

class MergeSort:
def merge(self, array, l, m, r):
    n1 = m - l + 1
    n2 = r - m

    esquerda = [0] * (n1)
    direita = [0] * (n2)

    for i in range(0, n1):
        esquerda[i] = array[l + i]

    for j in range(0, n2):
        direita[j] = array[m + 1 + j]

    i = 0
    j = 0
    k = l
    while i < n1 and j < n2:
        if esquerda[i] <= direita[j]:
            array[k] = esquerda[i]
            i += 1
        else:
            array[k] = direita[j]
            j += 1
        k += 1

    while i < n1:
        array[k] = esquerda[i]
        i += 1
        k += 1

    while j < n2:
        array[k] = direita[j]
        j += 1
        k += 1


def sort(self, array, l, r):
    if l < r:
        m = (l + (r - 1)) / 2
        self.sort(array, l, m)
        self.sort(array, m + 1, r)
        self.merge(array, l, m, r)

MAIN

tamanho = len(valores) - 1

mergeSort = MergeSort()
mergeSort.sort(valores, 0, tamanho)
    
asked by anonymous 30.06.2017 / 17:15

1 answer

2

In Python 3, divisions return real numbers. For integer division, use // :

(l + (r - 1)) / 2 # se (l + (r - 1)) for ímpar, retorna x.5
(l + (r - 1)) // 2 # se (l + (r - 1)) for ímpar, retorna o x acima, sem a parte decimal

See working on ideone

    
30.06.2017 / 17:43