This is quite a weird/silly question so if anyone as a better title name, please request an edit.
I've created a function that returns the product of numbers in a list.
When testing this function, I tried lists that that included intergers and reals(floats), such as items = [1,2.0,3,4.0]
Function:
items = [1.0, 2, 3.0, 10, "a"]
def mult1(items):
total = 1
for i in items:
total = total * i
return total
print mult1(items)
This function above works with items being [1.0, 2, 3.0, 10] and the output of that particular list being 60.0.
I've studied Standard ML where you can only generally have a list of a particular type (I'm sure there's code out there that somehow makes my statement irrelevant), so intrigued to find out what would happen if I entered a string as a list item, I did, and got an error (I expected to get an error because you can't multiply a string with a number).
However, the error I received has confused me:
TypeError: can't multiply sequence by non-int of type 'float'
This error has confused me. I understand that a string cannot be multiplied, but does this also suggest that all of the items in the list are considered a float despite some looking like integers?
I thought that the error should suggest it cannot compute a type that is not a float or not an integer, but to me (probably wrong) it seems like it's suggesting that it can't multiply the list by a a type that is not an integer that is also not of type float?
To me this sounds like each element has two types, integer and float.
You're getting this error because you are (perhaps unintentionally) multiplying a sequence (list, str, tuple) by a float.
>>> a = [1, 2]
>>> a * 2
[1, 2, 1, 2]
>>> a * 2.0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'
>>>
This error occurs because you can actually multiply some non-number types by ints, but not by floats. So if your product function looks something like:
def product(l):
prod = l[0]
for x in l[1:]:
prod *= x
return prod
and your list looks like this : l = ['this string',3,2.0]
then your iterations will show the following:
>>> def product(l):
prod = l[0]
for x in l[1:]:
prod *= x
print(prod)
return prod
>>> l = ['this string',3,2.0]
>>> product(l)
this stringthis stringthis string
Traceback (most recent call last):
File "<pyshell#69>", line 1, in <module>
product(l)
File "<pyshell#67>", line 4, in product
prod *= x
TypeError: can't multiply sequence by non-int of type 'float'
note that the first iteration is allowed because str*int is a valid expression (so is list*int and tup*int etc) and so prod is still valid but is a STRING, not an int or float. then when you DO try to do a str*float expression, the TypeError will occur.
You can multiply a string but only by an int, you see the error as you are trying to multiply a string by a float:
In [7]: "foo" * 2
Out[7]: 'foofoo'
In [8]: "foo" * 2.0
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-3128e6ce951c> in <module>()
----> 1 "foo" * 2.
TypeError: can't multiply sequence by non-int of type 'float'
In your particular case you are trying to multiply a from your list by a float:
[1.0, 2, 3.0, 10, "a"]
^
error
Total starts out an int but when you multiply an int by a float you get a float so total = total * 1.0 -> 1.0:
In [9]: 1 * 1.0
Out[9]: 1.0
Related
What am I doing wrong to get this error using the sum function in Python:
student_heights =input("Input a list of student heights ").split()
a=sum(student_heights)
print(a)
User input: 12 13 14 15
Error:
Traceback (most recent call last)
File "main.py", line 2, in <module>
TypeError unsupported operand type(s) for +:'int' and 'str'
The elements in your list are strings (that's how they return from input() from the console). You can, for example, convert them to integers:
a = sum(int(element) for element in student_heights)
Then you can sum them.
your variable student_heights is a type of list. A list accept string values. So we need to iterate through the list.
student_heights = input("Input a list of student heights ").split()
a = sum(int(i) for i in student_heights)
print(a)
I was trying to pass input into an array but it throws an error.
I already defined the value type in the array. I assigned the array with 'i' and also passed the int type value.
>>> import array as arr
>>> a = arr.array('i', [int(input())])
print(a)
Here's the error that I'm getting:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
a = arr.array('i', [int(input())])
ValueError: invalid literal for int() with base 10: 'print(a)'
You're typing this into a REPL environment, so each time you type a line, it runs (more or less), so when you enter the line:
a = arr.array('i', [int(input())])
The line after that is expecting the input for input, not the next line of code. Because you then type print(a) you're passing the value "print(a)" to int, essentially:
a = arr.array('i', [int("print(a)")])
Obviously "print(a)" is not a base 10 number so int is failing because "p" is not a character in base 10 (the digits 0 to 9 are the only valid digits).
To resolve this you need to pass a value for the input before continuing with your code:
>>> import array as arr
>>> a = arr.array('i', [int(input())])
5
>>> print(a)
array('i', [5])
import math
a=[100,4,5,10,3,1]
def swap(a,b):
temp=a
a=b
b=temp
for i in range(len(a),int(len(a)/2),-1):
l=i
print l
print int(math.ceil(int((l)/2.0)))
print a[int(math.ceil(int((l)/2.0)))]
print math.ceil(a[int((l)/2.0)])
print a[l-1]
while(l>1 and a[l-1] < a[int(math.ceil(int((l)/2.0)))]):
swap(a[l-1],a[int(math.ceil(int((l)/2.0)))])
print l
l= math.ceil(int((l))/2.0)
print a
Output:
6
3
10
10.0
1
6
Traceback (most recent call last):
File "heap.py", line 15, in <module>
while(l>1 and a[l-1] < a[int(math.ceil(int((l)/2.0)))]):
TypeError: list indices must be integers, not float
I have checked many questions on stackoverflow with same query, I
tried using the // as well but the error is persistent. I am using the
int value as I printed and tested. Can anyone redirect me to a
question with similar issue( if this duplicate) or help me with this
error?
I'm new to run-length coding and need help. I've been given a run-length string of a series of integer followed by characters that include letters/characters.
For example, I have a string:
1-4c8k2)
And I need to convert it into:
-cccckkkkkkkk))
What I've done is convert the run-length string into a list of tuples:
[('1','-'),('4','c'),('8','k'),('2','c')]
And tried creating a function which would convert it into a string however I get a TypeError: can't multiply sequence by non-int of type 'str'.
def decode(lst):
q = ''
for count, character in lst:
q += count * character
return q
I'm trying to think of a way to improve space complexity instead of creating a new list of tuples and more so, trying to resolve this TypeError.
I suspect that what has happened is you forgot to convert the counts into ints:
>>> 3 * 'a'
'aaa'
>>> '3' * 'a'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'
>>> int('3') * 'a'
'aaa'
You try through this way :
lst = [('1','-'),('4','c'),('8','k'),('2','c')]
def decode(lst):
q = ''
for count, character in lst:
q += int(count) * character
return q
print(decode(lst))
Output :
-cccckkkkkkkkcc
Check this code here
I'm trying to store a time value in an array, but it gives me an error every time, even when I try to cast the float into an int. Here is the portion of my code:
EndTimes = [0,0,0,0]
...
EndTimes[TakenSlots] = int(time.time() + n)
But it just gives this error:
[error] TypeError ( list indices must be integers )
[error] --- Traceback --- error source first
line: module ( function ) statement
44: main ( craftTime ) EndTimes[TakenSlots] = tempInt
I tried this code just to see what it thought the value was:
tempInt = int(time.time() + n)
print tempInt
EndTimes[TakenSlots] = tempInt
And it just outputted 1412046180 (no decimal places, which seems like it should be an int)
Does anyone know what's happening? Is it a problem with the int() or the type of array I'm using? Thanks in advance!
This occurs because the list index ( list[index] = value ) must be an integer. It is probable that TakenSlots is not an int.
>>> l = [1,2,3]
>>> l[1.3] = 10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not float