minus-squareForcedSword@discuss.tchncs.detoPython@programming.dev•Python function to convert baking ingredient weights to fractional volume measurementslinkfedilinkarrow-up1arrow-down1·edit-21 year agoEasy, just asked ChatGPT: from pint import UnitRegistry ureg = UnitRegistry() def convert_weight_to_measurements(weight_in_grams): measurements = [ ('cup', 1), ('1/2 cup', 1/2), ('1/3 cup', 1/3), ('1/4 cup', 1/4), ('tablespoon', 1), ('teaspoon', 1), ('1/2 teaspoon', 1/2), ('1/4 teaspoon', 1/4) ] result = {} for measure, value in measurements: unit = ureg(measure) count = int(weight_in_grams / (value * unit.to('grams').magnitude)) if count > 0: result[measure] = count weight_in_grams -= count * (value * unit.to('grams').magnitude) return result # Example usage weight_in_grams = 240 result = convert_weight_to_measurements(weight_in_grams) print(f"Weight: {weight_in_grams} grams") print("Converted to:") for measure, count in result.items(): print(f"{count} {measure}") linkfedilink
Easy, just asked ChatGPT:
from pint import UnitRegistry ureg = UnitRegistry() def convert_weight_to_measurements(weight_in_grams): measurements = [ ('cup', 1), ('1/2 cup', 1/2), ('1/3 cup', 1/3), ('1/4 cup', 1/4), ('tablespoon', 1), ('teaspoon', 1), ('1/2 teaspoon', 1/2), ('1/4 teaspoon', 1/4) ] result = {} for measure, value in measurements: unit = ureg(measure) count = int(weight_in_grams / (value * unit.to('grams').magnitude)) if count > 0: result[measure] = count weight_in_grams -= count * (value * unit.to('grams').magnitude) return result # Example usage weight_in_grams = 240 result = convert_weight_to_measurements(weight_in_grams) print(f"Weight: {weight_in_grams} grams") print("Converted to:") for measure, count in result.items(): print(f"{count} {measure}")