Python Forum

Full Version: TypeError: can't multiply sequence by non-int of type 'float'
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi guys I'm having a problem with an assignment in my class we are now on using fullmatrix and sparce and I get this error in my code :

class Vector(object):
    def __init__(self, data):
        self.data = data
        self.rows = len(data)

    def __mul__(self, other):
        assert self.rows == other.rows
        return sum([vi * vj for vi, vj in zip(self.data, other.data)])

    def __rmul__(self, a):
        data = [a * d for d in self.data]
        return Vector(data)
    
    def __add__(self, other):
        assert self.rows == other.rows
        return Vector([i + j for (i, j) in zip(self.data, other.data)])

    def __sub__(self, other):
        assert self.rows == other.rows
        return Vector([i - j for (i, j) in zip(self.data, other.data)])

    def norm(self):
        return math.sqrt(self * self)

    def __str__(self):
        return '{0}'.format(self.data)
Error:
File "C:\Users\illar\Desktop\05.py", line 116, in <listcomp> data = [a * d for d in self.data] TypeError: can't multiply sequence by non-int of type 'float'
You should provide enough code to reproduce the issue. As-is, things are missing. You'll be more likely to get a fast response if you remove unnecessary details though.
Your __rmul__ method seems to try to multiply two things together without checking if that's appropriate. If one of the factors is a sequence and the other is float, you'll get this error.

>>> ['a', 'b', 'c'] * 3.0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'
Either fix your inputs or have your method massage a float into an int if that's more appropriate.
Change the "3.0" to just "3". Floats are decimal numbers.