Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Convert Feet and Inches to Feet decimals
- # Mike Kerry - Feb 2021 - [email protected]
- hlist = ["Height", "3 ft 4in", "4ft 1 in", "4ft", "3ft 9in", "3.5ft", "4ft 3 in", "3ft 7in"]
- total_inches = 0.0 # Accumulator for sum of heights in inches
- valid_heights = 0 # Count of valid height strings found
- for hs in hlist[1:]: # Process each cell except the first (which contains "height")
- x = hs.find("ft") # we expect to find the string "ft" in every cell
- if x < 0:
- print("Invalid cell: ", hs)
- continue
- valid_heights += 1 # Count one valid height string
- hs1 = hs[:x].strip() # extract everything before "ft" and strip off any leading and trailing spaces
- feet = float(hs1) # what's left can now be converted to a float value (no matter if integer or float)
- # Now extract any inches
- inches = 0 # start by assuming there are no inches specified
- y = hs.find("in")
- if y > 0: # was "in" found? (if not, y will be -1, and inches stays at zero)
- hs2 = hs[x+2:y].strip() # Extract everything between "ft" and "in" and strip it
- inches = float(hs2) # What's left can now be converted to inches as a float
- inches += feet * 12 # Compute total inches for one student
- total_inches += inches # compute sum of heights for all students in inches
- print("The average student height is {:.3f} inches".format(total_inches / valid_heights))
- total_feet = total_inches / 12.0 # convert to feet and decimals
- print("The average student height is {:.1f} feet".format(total_feet / valid_heights))
- # Output:
- # The average student height is 45.429 inches
- # The average student height is 3.8 feet
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement