What do I need to change about my program?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bugaboo
    New Member
    • Apr 2010
    • 1

    What do I need to change about my program?

    I'm trying to write a program that will determine the total number of lines, columns, digits, as well as the maximum and minimum number. However it returns the wrong data and can't count any negative numbers. My program is...


    Code:
    max = 0
    min = 0
    
    def getMaxMin(digitsList):
    	global max
    	max = digitsList[0]
    	global min
    	min  = digitsList[0]
    
    	for digit in digitsList:
    		if digit > max:
    			max = digit
    		if digit < min:
    			min = digit
    
    import sys
    
    def main():
    
    	filename = sys.argv[1]
    	file = open(filename,"r")
    	line = file.readline()
    
    	lines = 0
    	columns = 0
    	digits = 0
    	digitsList = []
    
    	while line != "":
    		line = line.strip('\n')
    		lines += 1
    		words = line.split('\t')
    
    		for word in words:
    			if word.isdigit():
    				digits += 1
    				digitsList.append(int(word))
    
    		columns = len(words)
    		line = file.readline()
    
    	getMaxMin(digitsList)
    	print "lines = ",lines
    	print "columns = ",columns	
    	print "digits = ",digits 
    	print "max = ",max
    	print "min = ",min
    
    main()

    And the files that I'm trying to use are

    Month Minimum Maximum Average
    Jan -16 -7 -11.5
    Feb -15 -5 -10
    Mar -8 1 -4
    Apr 0 11 6
    May 7 19 13
    Jun 12 24 18
    Jul 14 27 21
    Aug 14 26 20
    Sep 9 20 15
    Oct 3 14 9
    Nov -2 5 2
    Dec -12 -4 -8



    and

    Country Gold Silver Bronze Total
    US 9 15 13 37
    GE 10 13 7 30
    CA 14 7 5 26
    NO 9 8 6 23
    AU 4 6 6 16
    RF 3 5 7 15
    KO 6 6 2 14
    CH 5 2 4 11
    SW 5 2 4 11
    FR 2 3 6 11


    Anyone who can help me out??
    Last edited by bvdet; Apr 7 '10, 06:02 AM. Reason: Fix code tags
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    The example code attempts to type cast each element to int which makes it easy to determine the max and min. It also uses str method split() like yours, but assumes a whitespace delimiter.
    Code:
    def conv_int(s):
        try:
            s = int(s)
        except: pass
        return s
    
    fn = "text6.txt"
    f = open(fn)
    labels = f.readline().strip().split()
    lineList = []
    for line in f:
        lineList.append([conv_int(s.strip()) for s in line.strip().split()])
    
    num_cols = len(labels)
    max_max = max([item[2] for item in lineList])
    min_min = min([item[1] for item in lineList])
    print num_cols
    print max_max
    print min_min

    Comment

    Working...