Typeerror: can’t Multiply Sequence by non-int of type 'float'

Asked

Viewed 860 times

1

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

Erro completo

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)

LEADING

tamanho = len(valores) - 1

mergeSort = MergeSort()
mergeSort.sort(valores, 0, tamanho)

1 answer

2


In Python 3, divisions return real numbers. For entire 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

Behold functioning on the ideone

  • 1

    Wow, I would spend most of the day trying to figure that out. Thank you so much!

  • I only noticed when I read the tag [tag:python-3.x]. So I went for some division that justified this

Browser other questions tagged

You are not signed in. Login or sign up in order to post.