Python float list of list value comparison - python

I have started to look into python and am trying to grasp new things in little chunks, the latest goal i set for myself was to read a tab seperate file of floats into memory and compare values in the list and print the values if difference was as large as the user specified. I have written the following code for it so far:
#! /usr/bin/env python
value = raw_input('Please enter a mass difference:')
fh = open ( "values" );
x = []
for line in fh.readlines():
y = [float for float in line.split()]
x.append(y)
fh.close()
for i in range(0,len(x)-1):
for j in range(i,len(x)):
if x[j][0] - x[i][0] == value:
print x[i][0],x[j][0]
The compiler complains that i am not allowed to substract strings from strings (logically) but my question is ... why are they strings? Shouldn't the nested list be a list of floats as i use float for float?
Literal error:
TypeError: unsupported operand type(s) for -: 'str' and 'str'
I would greatly appreciate if someone can tell me where my reasoning goes wrong ;)

Try this in place of your list comprehension:
y = [float(i) for i in line.split()]
Explanation:
The data you read from the file are strings, to convert them to other types you need to cast them. So in your case you want to cast your values to float via float() .. which you tried, but not quite correctly/successfully. This should give you the results you were looking for.
If you have other values to convert, this syntax will work:
float_val = float(string_val)
assuming that string_val contains valid characters for a float, it will convert, otherwise you'll get an exception.
>>> float('3.5')
3.5
>>> float('apple')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for float(): apple

The list comprehension isn't doing what you think it's doing. It's simply assigning each string to the variable float, and returning it. Instead you actually want to use another name and call float on it:
y = [float(x) for x in line.split()]

Error 1: y = [float(x) for x in line.split()] or simply map(float,lines.split())
Error 2: if x[j][0] - x[i][0] == float(value): #you didn't converted value to a float

Related

Why does the following evaluate to a ValueError in python?

We were coding something awhile ago and we came across a small problem. We wanted to try to convert float numbers to integers
Here is the code:
x = int(input(())
print x
We tried the code and put 5.5. It evaluated to a ValueError. Logically, it is sound in logic. But if we try the following code:
x = int(float(input(())) OR x = int(5.5), it evaluates to a value of 5.
Why does this happen?
In the first case, you are calling int("5.5"), because input() returns a string. that's a ValueError because 5.5 is not an int, and the designers of python decided not to do any implicit casting.
In the second case, you care calling float("5.5"), which is 5.5 because "5.5" can be converted to a float as you asked, and then int(5.5), which is the result of converting a float to an int (python uses truncation for this; you can call round() instead if that's not what you want).
The third case is just the same as the second step of the second case.
Its because of input() takes the value as a string data type. When you are taking "5" then converting into int() works but converting string input "5.5" to int() will give error as this is not supported by python. In such a case, you have to first convert it to float() and then int() to get an integer value.
I think x = int(5.5) didn't lead to any value error. First problem is, yeah, you cannot directly compare it an input result with int or float. To make sure it let's do this little experiment:
>>> x = input()
>>? 20
>>> print(type(x))
>>> <class 'str'>
From this experiment, you see that even you enter "any numerical" to input, it will return your input as string. And let's check what's going on with int(input()) operation:
x = int(input())
5.5
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.5'
This problem happen when you try to 'directly' convert a float to integer. Python cannot convert literally float to int directly. There's another trick to help this, by assign float as the number original datatype. This is happen when and let's see if we add float as another parser :
x = int(float(input()))
5.5
print(type(x))
<class 'int'>
The solution is simple, just directly parse your input as int, then compare it:
x = int(float(input()))
if x == 5 or x == int(5.5):
#do something
Hope it will help you. Good Luck!

how to convert a list of floats to int in python ;err int() argument must be a string, a bytes-like object or a number, not 'list'

I'm trying to convert my list of floats to ints, but I keep getting the error
int() argument must be a string, a bytes-like object or a number, not 'list'
This is my code, and values is the list in floats.
values = [my_random() for x in range(num_trials)]
vals_to = [int(x*100) for x in values]
and I'm doing this in jupyter notebook. When I try samples they turn out fine, but I'm so confused on why this particular code of list is giving me this error.
Can someone please point me in the right direction?
First, you need to make sure that your function my_random() returns a float number.
Anyway, let's say you have a list of float numbers
mylist = [3.1415, 74.2, 345.03, 98.9]
There are many ways to achieve your task. For example,
res = [int(i) for i in mylist] # 1 List comprehension
res = list(map(int, mylist)) # 2 Map
For more control on how to round each number, you can use math
import math
res = list(map(math.ceil, mylist)) # Round up
res = list(map(math.floor, mylist)) # Round down

String Indices Must be Integers in Python

I am using Python to solve a contest problem. I am getting this error. I am fairly new and inexperienced with Python.
for kek in sorteddic:
lengthitem = int(len(kek))
questionstring = start[0, lengthitem]
kek is essentially the "item" in "sorteddic" which is an array of strings.
The error I am getting is:
questionstring = start[0, lengthitem]
TypeError: string indices must be integers
Can someone please help? Thanks.
It's because the item you're trying to use as an index, 0, lengthitem, is not an integer but a tuple of integers, as shown below:
>>> x = 1 : type(x)
<class 'int'>
>>> x = 1,2 : type(x)
<class 'tuple'>
If your intent is to get a slice of the array (not entirely clear but I'd warrant it's a fairly safe guess), the correct operator to use is :, as in:
questionstring = start[0:lengthitem]
or, since 0 is the default start point:
questionstring = start[:lengthitem]
The following transcript shows how your current snippet fails and the correct way to do it:
>>> print("ABCDE"[1])
B
>>> print("ABCDE"[1,3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
>>> print("ABCDE"[1:3])
BC
Slice notation uses colons, not commas (unless you are in numpy where commas separate dimensions in slices, athough under the hood that is treated as a tuple of slice objects). So use:
questionstring = start[0:lengthitem]

How to sum a list of numbers stored as strings

Having a list of numbers stored as strings how do I find their sum?
This is what I'm trying right now:
numbers = ['1', '3', '7']
result = sum(int(numbers))
but this gives me an error:
Traceback (most recent call last):
File "main.py", line 2, in <module>
result = sum(int(numbers))
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
I understand that I cannot force the list to be a number, but I can't think of a fix.
int(numbers) is trying to convert the list to an integer, which obviously won't work. And if you had somehow been able to convert the list to an integer, sum(int(numbers)) would then try to get the sum of that integer, which doesn't make sense either; you sum a collection of numbers, not a single one.
Instead, use the function map:
result = sum(map(int, numbers))
That'll take each item in the list, convert it to an integer and sum the results.
If you prefer a less functional style, you can use a generator expression
result = sum(int(x) for x in numbers))

Why doesn't join() automatically convert its arguments to strings? When would you ever not want them to be strings?

We have a list:
myList = [1, "two"]
And want to print it out, normally I would use something like:
"{0} and {1}".format(*myList)
But you could also do:
" and ".join(myList)
But unfortunately:
>>> " and ".join(myList)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
Why doesn't it just automatically convert the list it receives to strings?
When would you ever not need it to convert them to strings? Is there some tiny edge case I'm missing?
From the Zen of Python:
Explicit is better than implicit.
and
Errors should never pass silently.
Converting to strings implicitly can easily hide bugs, and I'd really want to know if I suddenly have different types somewhere that were meant to be strings.
If you want to explicitly convert to strings, you can do so using map(), for example:
''.join(map(str, myList))
The problem with attempting to execute something like x = 4 + "8" as written is that the intended meaning is ambiguous. Should x contain "48" (implicitly converting 4 to str) or 12 (implicitly converting "8" to int)? We can't justify either result.
To avoid this confusion, Python requires explicit conversion of one of the operands:
>>> x = str(4) + "8"
>>> y = 4 + int("8")
>>> print x
48
>>> print y
12
Using the correct type is part of programming in Python. A general built-in like print does do the conversion (if the class supports __str__), which is where you should be doing it:
Let print do the work:
print(*myList, sep = " and ")
That's for Python 3, if you are still on Python 2 then use:
from __future__ import print_function

Categories

Resources