简体   繁体   中英

How can I add convert a decimal into a fraction and then add that in a list?

I'm trying to create code where there is a cooking recipe and if the user wants to change the servings, they can do so, causing the amount for each ingredient to lessen or increase. My code so far is:

from fractions import Fraction
french_toast_recipe = [1, 1, 1/2, 1/4, 4] # this is the actual recipie without the ingredients and just the measurements so it's easy to divide

user_descicion = input(" This recipe makes four servings of french toast, would you like to change \n
                 the servings? If no type \"n\" otherwise type anything ")

if user_descicion == "n":
    print("Your recipie is: 1 egg, 1 teaspoon of vanilla extract, 1/2 teaspoon of ground cinnamon, \n 
    and finally 4 slices of bread")
else:    
    user_servings = int(input("How many servings would you like?"))
    divide_recipe = 4 / user_servings
    new_recipe = []
    for i in french_toast_recipe:
        new_recipie.append(Fraction(i/divide_recipe))
        
    
    print(new_recipe)

However, it's printing out like this when I input the servings as 6 [Fraction(3, 2), Fraction(3, 2), Fraction(3, 4), Fraction(3, 8), Fraction(6, 1)], where I want it to be [3/2, 3/2, 3/4, 3/8 and 6/1], can anyone help?

The problem is that when printing the contents of a list, the Python calls repr() on each item to determine how to print it. repr() is intended to produce a representation of the object, usually what you'd put into Python to get that value. For the Fraction class this looks like the class instantiation.

So there are a couple of ways to get around this:

  • Create a Fraction subclass that returns a repr() like the original class's str() , then use that where you use Fraction now.
class MyFraction(fractions.Fraction):
    __repr__ = fraction.Fraction.__str__
  • Don't print a list of the fractions; rather, print a list of the strings of each fraction.
print([str(x) for x in new_recipe])

There are other ways to approach this. As you improve the program and start working on making the output nicer; eventually you will want to print the numbers with the ingredients, and at that point you will likely be using a loop over the ingredients and just printing a single fraction at a time. That already works the way you want, so you won't actually need either of these solutions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM