Python:Reading (int,float,comp,bool) from file

  • Context: Python 
  • Thread starter Thread starter Raghav Gupta
  • Start date Start date
  • Tags Tags
    File
Click For Summary

Discussion Overview

The discussion revolves around reading comma-separated numeric values (int, float, complex, bool) from a file, storing them in a list, sorting the list without using built-in functions, and writing the output to a file. Participants are exploring how to handle typecasting of different numeric types and the implications for sorting.

Discussion Character

  • Homework-related
  • Technical explanation
  • Debate/contested

Main Points Raised

  • One participant expresses difficulty in typecasting float values to int, questioning how to handle this with conditions.
  • Another participant asks why typecasting to int is necessary, suggesting that the problem description does not require it.
  • A later reply suggests that sorting requires numeric types, but acknowledges that comparisons could be done as strings, leading to lexicographic order.
  • One participant points out that the input file contains strings, not actual numeric types, and explains the need to determine the type of each value before typecasting.
  • Another participant proposes a method to identify the type of each value by attempting to assign it to predefined variables of different types (complex, float, int, bool) and catching exceptions.
  • There is a note that sorting complex numbers with real numbers is not straightforward, as they are not directly comparable.

Areas of Agreement / Disagreement

Participants do not reach a consensus on the necessity of typecasting to int, with some arguing for its necessity while others suggest it may not be required. The discussion remains unresolved regarding the best approach to handle the typecasting and sorting of mixed numeric types.

Contextual Notes

Participants highlight the challenge of distinguishing between different numeric types when reading from a file, as the values are initially read as strings. There are also concerns about the implications of sorting mixed types, particularly with complex numbers.

Raghav Gupta
Messages
1,010
Reaction score
76

Homework Statement


Read a comma separated numeric (int, float, comp, bool) values from a file and store each
comma separated value in a list[/B]. Sort the list (without using in-built sort/sorted function)
and write it to output file in comma separated format.

In my attempt I am not able to do the bold part in the question. That is if float value is there in file then it cannot be typecasted to int. How do I typecast with conditions?

Homework Equations


NA

The Attempt at a Solution


Python:
f=open("qwerty.txt","r")
y=[]
for line in f:
    x=line.split(',')
    for val in x:
       y.append(int(val))  # Here if float is stored in file then it cannot be typecasted to int.
for i in range(len(y)-1):    # Doing bubble sort
    for j in range(len(y)-i-1):
        if y[j]>y[j+1]:
            y[j],y[j+1]=y[j+1],y[j]
f.close()
f=open("output.txt","w")
f.write(str(y)[1:-1])
f.close()
 
Technology news on Phys.org
Raghav Gupta said:

Homework Statement


Read a comma separated numeric (int, float, comp, bool) values from a file and store each
comma separated value in a list[/B]. Sort the list (without using in-built sort/sorted function)
and write it to output file in comma separated format.

In my attempt I am not able to do the bold part in the question. That is if float value is there in file then it cannot be typecasted to int. How do I typecast with conditions?

Homework Equations


NA

The Attempt at a Solution


Python:
f=open("qwerty.txt","r")
y=[]
for line in f:
    x=line.split(',')
    for val in x:
       y.append(int(val))  # Here if float is stored in file then it cannot be typecasted to int.
for i in range(len(y)-1):    # Doing bubble sort
    for j in range(len(y)-i-1):
        if y[j]>y[j+1]:
            y[j],y[j+1]=y[j+1],y[j]
f.close()
f=open("output.txt","w")
f.write(str(y)[1:-1])
f.close()
Is the idea just to read values from the file and store them in a list? If so, why do you need to cast a floating point value to an integer value? The problem description you have doesn't mention doing this.
 
Mark44 said:
Is the idea just to read values from the file and store them in a list? If so, why do you need to cast a floating point value to an integer value? The problem description you have doesn't mention doing this.
But we have to sort, so we have to convert it into numeric type.
EDIT: Ok, so we can compare them as strings only. It would compare lexicographically based on ASCII values but if we store them in file again, it is stored something like this-
'1' , '2+j', '3.5', '4', 'FALSE', 'TRUE'
This is storing the list contents in string format. I want output like this-
1, 2+j, 3.5, 4, FALSE, TRUE
without quotes
For that I have to typecast finally?
 
Last edited:
Raghav Gupta said:
Python:
f=open("qwerty.txt","r")
y=[]
for line in f:
    x=line.split(',')
    for val in x:
       y.append(int(val))  # Here if float is stored in file then it cannot be typecasted to int.
The problem is that the text file doesn't contain floats or integers or complex numbers -- it contains text. Your variable x is a list that contains strings. For example, if the first line of the input file is 3.5, 2, true, the list x will look like ['3.5', '2', 'true'].
The reason that int(val) throws an exception (ValueError) is that int() can't be used on strings. For the same reason, float(), bool(), and complex() will fail when applied to strings.

What you need to do for each value you get from the file is figure out if it's a complex or float or integer or Boolean. One way to do this is to have four other variables, with each initialized to a value of one of these four types (complex, float, integer, Boolean).
Python:
v_cplex = 1+2j
v_float = 1.5
v_int = 1
v_bool = True
There's nothing special about the initializations I did above. I just want four variables with each of a specific type.

For a given val, try assigning it to each of the above variables. If you assign val to f_float, for example, and get an error (ValueError), you know that val isn't a float value. After you determine that val is, say, a float, append v_float to your list y.

Edit: One more thing. If you write the various values to a list as numbers, you won't be able to sort them, as complex numbers aren't comparable to real variables (such as int, float, bool).
 
Last edited:

Similar threads

  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 16 ·
Replies
16
Views
4K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 17 ·
Replies
17
Views
3K
  • · Replies 6 ·
Replies
6
Views
2K
  • · Replies 75 ·
3
Replies
75
Views
6K
  • · Replies 9 ·
Replies
9
Views
3K
Replies
1
Views
3K
  • · Replies 5 ·
Replies
5
Views
2K
  • · Replies 5 ·
Replies
5
Views
2K