Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ######################################################################################
- # Simple file read/math
- #
- # A simple example using file read, modulo, for loop, if/else, and "input sanitization."
- # Basically reads in a comma separated list of values, and outputs count, sum, average,
- # and number of evens and odds. Also notes the invalid inputs.
- #
- # Tested on a file with the following data:
- # '100', '12', '22', '64', '2', '57', '99', '323', 'w', '6', '967', '3', '-2', '3.0', '5', '89', '32', '667', '3'
- ######################################################################################
- # NOTE: A cleaner version of http://pastebin.com/kwtVP351
- # Open the file into a file pointer
- fp = open("numbers.txt","r")
- # Use the file pointer to read the contents of the file into a string variable
- text = fp.read()
- # Close the file pointer
- fp.close()
- # Use the split() function to separate the comma-separated text file into a list
- list = text.split(",")
- # Output the list
- print "This is the list:",list
- print
- # Initialize our statistics variables
- average = 0
- # Loop through the list of numbers and process each number
- # Validate for whole numbers only
- sanitizedList = [int(item) for item in list if item.isdigit()]
- errorList = [item for item in list if not (item.isdigit())]
- # Test for evens and odds using the modulo operation
- # We will calculate the number of odds using subtraction
- evensList = [item for item in sanitizedList if item % 2 ==0]
- # Check for any errors
- if len(errorList)>0:
- # Output an error message
- print "Non whole numbers detected:",errorList
- # If there was more than one valid value, calculate the average using the sum and count variables
- # Explicitly convert one value to float so that we get a more accurate average
- # Without this, the value would be rounded to the nearest whole number.
- listCount = len(sanitizedList)
- if listCount>0:
- average = float(sum(sanitizedList))/listCount
- #Output the results of the calculations
- print
- print "File Read Statistics"
- print "--------------------"
- print "Total number of whole numbers:",listCount
- print "Sum of whole numbers:", sum(sanitizedList)
- print "Average of whole numbers:", average
- print "Total number of even whole numbers:", len(evensList)
- print "Total number of odd whole numbers:", listCount - len(evensList)
- print "Total number of input file errors:", len(errorList)
- print
- raw_input("Press Enter to exit")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement