Hi,
I have written this code to generate the maximun number from a number of coloumns (say 4 coloumns) in a list. The code is not handling negative number well and so keep generating the negaive number to be greater eg -8 > 5 which is wrong. Why is this happening?

file_in = open( 'cont.dat',"r")
data_in=file_in.readlines()
file_in.close()
coloumn=[]
for line in data_in:
    data=line.split()
    ncoverage=len(data)
    maxval=data[0]
    maxid=0
    for j in xrange(0,ncoverage,1):
        if data[j]>= maxval:
            maxval=data[j]
    print maxval
data=line.split()
maxval=data[0]

because you are using strings instead of integers. So converting to an integer would look like this.

file_in = open( 'cont.dat',"r")
data_in=file_in.readlines()
file_in.close()
coloumn=[]
for line in data_in:
    data=line.split()
    ncoverage=len(data)

    ##   convert to integer
    maxval=int(data[0])

    maxid=0
    for j in xrange(0,ncoverage,1):

        ##   convert to integer
        if int(data[j])>= maxval:
            maxval=int(data[j])
    print maxval

thank s for the code. I have tried this but i keep getting the following error

maxval=int(data[0])
ValueError: invalid literal for int() with base 10: '-0.0539723'

However when i use float() instead, it works. Do you understand this error.

thank s for the code. I have tried this but i keep getting the following error

maxval=int(data[0])
ValueError: invalid literal for int() with base 10: '-0.0539723'

However when i use float() instead, it works. Do you understand this error.

'-0.0539723' is not a valid integer since it is not a whole number. It is a floating point number, which requires the float() conversion. int() only works on whole numbers.

>>> #okay so int('-0.539723') doesn't work
>>> int('-0.0539723')

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    int('-0.0539723')
ValueError: invalid literal for int() with base 10: '-0.0539723'
>>> myFloat = float('-0.0539723')
>>> print myFloat
-0.0539723
>>> int(myFloat)
0
>>>

int does work for non-whole numbers, but you can't go straight from a float like string to an integer. Go to float, and then to int. Also, calling int on anything that is less than 1 or larger than -1 will result in 0. You may want to use float instead of int to be more precise. Also, int doesn't round, it just truncates. So int(0.5) returns 0. BUT, round(0.5) returns 1.0, so to get the rounded version of a float in int form you could say int(round(float_num))

You could also check out the math module, which has the functions ceil and floor. ceil(0.5) returns 1.0, floor(0.5) returns 0.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.