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

  • Thread starter Thread starter Raghav Gupta
  • Start date Start date
  • Tags Tags
    File
AI Thread Summary
The discussion revolves around reading comma-separated numeric values (integers, floats, complex numbers, and booleans) from a file, storing them in a list, sorting the list without using built-in sorting functions, and writing the sorted values back to an output file. The main challenge highlighted is the inability to typecast values directly to integers when floats are present, leading to ValueErrors. Participants suggest that instead of casting directly, one should determine the type of each value (integer, float, complex, boolean) using conditional checks. It is emphasized that since the values are read as strings, they must be evaluated to their respective types before sorting. Additionally, it is noted that sorting mixed types (like complex numbers with real numbers) is not feasible, which complicates the sorting process. The final output should be formatted correctly without quotes around the values.
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:
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I had a Microsoft Technical interview this past Friday, the question I was asked was this : How do you find the middle value for a dataset that is too big to fit in RAM? I was not able to figure this out during the interview, but I have been look in this all weekend and I read something online that said it can be done at O(N) using something called the counting sort histogram algorithm ( I did not learn that in my advanced data structures and algorithms class). I have watched some youtube...

Similar threads

Back
Top