Python Forum
TypeError: can't multiply sequence by non-int of type 'float' - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: TypeError: can't multiply sequence by non-int of type 'float' (/thread-25572.html)



TypeError: can't multiply sequence by non-int of type 'float' - DimosG - Apr-03-2020

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'



RE: TypeError: can't multiply sequence by non-int of type 'float' - micseydel - Apr-03-2020

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.


RE: TypeError: can't multiply sequence by non-int of type 'float' - bowlofred - Apr-03-2020

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.


RE: TypeError: can't multiply sequence by non-int of type 'float' - michael1789 - Apr-04-2020

Change the "3.0" to just "3". Floats are decimal numbers.