Reputation:
I was basically trying to recreate some algorithm. An user is supposed to enter values from the keyboard and they get converted into a list. After that I wanted to add the two smallest value from list and then repeat until I get the value of 1. But, I get the following error:
Traceback (most recent call last):
********* line 13, in <module>
while n[:1] != 1.0:
TypeError: 'float' object is not subscriptable
This is my code:
a = input("Enter values: \n")
n = list(map(float, a.split(' ')))
OK = 1
if OK:
while n[:1] != 1.0:
n = sorted(n)
print(n)
n[1] = n[0] + n[1]
n = n.pop(0)
print(n)
Upvotes: 0
Views: 517
Reputation: 8917
I assume that it's printing n
once?
In your second last line you do n = n.pop(0)
which means that n
, which was previously a list
is now a float
. And you can't call n[:1]
if n
is a float.
I'm not 100% what you're trying to achieve, but try this:
a = input("Enter values: \n")
x = list(map(float, a.split(' ')))
OK = 1
if OK:
n = x.pop(0)
while x and n != 1.0:
x = sorted(x)
print(x)
x[1] = x[0] + x[1]
n = x.pop(0)
print(x)
Upvotes: 1
Reputation: 32189
Firstly, you probably want to use <
for your condition instead of an exact !=
check since you're dealing with imprecise floats. Secondly, you keep changing the type of n
between a list and a float (by assiging it the value of pop
). Here's a fixed version of your code:
a = input("Enter values: \n")
n = list(map(float, a.split(' ')))
OK = 1
if OK:
while n[0] < 1.0: # Access the first element with [0] not by slicing with [:1]
n = sorted(n)
print(n)
n[1] = n[0] + n[1]
n.pop(0) # Here don't assign this result back to n
print(n)
I won't address the case where the values entered are greater than 1 as mentioned by the others and I'll trust that you're handling it properly in the rest of your code
Here's a sample run:
Enter values:
0.2 0.1 0.4 0.6 0.4 0.7
[OUTPUT]
[0.1, 0.2, 0.4, 0.4, 0.6, 0.7]
[0.30000000000000004, 0.4, 0.4, 0.6, 0.7]
[0.4, 0.6, 0.7, 0.7000000000000001]
[1.0, 0.7, 0.7000000000000001]
Upvotes: 3