Skip to content

Instantly share code, notes, and snippets.

@jaredhabeck
Created January 9, 2018 20:32
Show Gist options
  • Save jaredhabeck/7a69308175518e0833c90c11e9f7d7ee to your computer and use it in GitHub Desktop.
Save jaredhabeck/7a69308175518e0833c90c11e9f7d7ee to your computer and use it in GitHub Desktop.
cooking converter
# Cooking Converter Project Ver1.03
"""Changelog
ver1.03
- removed clearscreen function for now
- units now print full names
- script gives plural unit when necessary
- fractions implemented but not printing human-readable
"""
from __future__ import division
from fractions import Fraction
import math
"""Maps unit abbreviations to their full names."""
metric_units_dict = {
"gram" : "gram",
"ml" : "milliliter",
"lt" : "liter",
"oz" : "ounce",
"pnt" : "pint",
"qrt" : "quart",
"gal" : "gallon"
}
imperial_units_dict = {
"tsp" : "teaspoon",
"tbsp" : "tablespoon",
"cup" : "cup",
"lb" : "pound"
}
print "What is the amount you are converting from?"
in_amount = float(raw_input("> "))
print "\nWhat is the unit you are converting from?"
print "gram | ml | lt | tsp | tbsp | oz | cup | pnt | qrt | gal | lb?"
in_unit = raw_input("> ")
print "\nWhat is the unit you are converting to?"
print "gram | ml | lt | tsp | tbsp | oz | cup | pnt | qrt | gal | lb?"
out_unit = raw_input("> ")
"""Takes the user input and finds the full unit-out name."""
#full_unitout_name = units_dict.get(out_unit, "Not found")
full_unitout_name = metric_units_dict.get(out_unit, imperial_units_dict.get(out_unit, "Not found"))
"""Converts the given amount to the desired unit."""
# all units given in relation to the gram.
def unit_conversion(in_amount, in_unit, out_unit):
unit_multiplier = {
'gram': 1.,
'ml' : 1.,
'lt' : 1000.,
'tsp' : 4.2,
'tbsp': 14.8,
'oz' : 28.34,
'cup' : 236.5,
'pnt' : 473.2,
'qrt' : 946.3,
'gal' : 3785.,
'lb' : 453.6,
}
return in_amount*unit_multiplier[in_unit]/unit_multiplier[out_unit]
converted = unit_conversion(in_amount, in_unit, out_unit)
"""Appends and 's' to a solution > 1."""
def pluralize_unit():
if converted > 1.0:
return full_unitout_name + 's'
else:
return full_unitout_name
"""Converts improper fractions to mixed numbers."""
# Can this be placed inside the def unit_conversion function?
def fractionalize(converted):
# if it's in the metric dict just return it floated to 2 decimals
# else if it's in the imperial dict, do fraction work
if out_unit in metric_units_dict:
return "\n%.2f" % (converted)
else:
whole_number = math.floor(converted)
to_fraction = (converted % whole_number) / 1
if whole_number > 0:
return "%s and %s" % (int(whole_number), Fraction(to_fraction).limit_denominator(10))
else:
return "%s" % Fraction(to_fraction).limit_denominator(10)
"""Prints the solution to the screen for the user."""
print "\n%s %s\n" % (fractionalize(converted), pluralize_unit())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment