Вопрос

I am trying to write a program that calculates nutrition level in food.Suppose I have this data(may be incorrect)

10 grams of bread has 68 mg sodium.
1 medium slice is 50 grams.

1 cup of milk has 98 mg sodium
1 cup of milk is 236 ml(or 244 grams)
which means 10 grams of milk has 0.004 grams of Sodium

The user may enter number of slices or grams of bread he ate or if it is milk -how many cups or how many ml of milk he drank

So,how should I design the data structure? should I keep a single unit measure internally like grams and convert slice,ml,cup etc into that?

    food details ={ 
     'whitebread':{'unit':10,'slice':50,'sodium':0.068},
     'milk':{'unit':10,'cup':244,'sodium':0.004},...
     }
Это было полезно?

Решение

Definitely, you should convert internally to a single measurement unit and convert at input and at output.

It is even more important in python than in other as it is dynamically typed - you cannot explicitly declare what type do a function use or return. Consider an example:

def get_sodium_for_bread(quantity_of_bread):
    ...
    return quantity_of_sodium

You cannot explicitly define type of quantity_... variable like in C (miligrams_t get_sodium(slices_t bread)). If you use different units you will get lost very quickly.

It would be the simpliest if you used a single unit for everything if possible, e.g. grams

food_props_per_gram = {
    'bread': {'sodum': 0.000012},
    'milk': {'sodium': 0.00032}
}

units_to_grams = {
    'slice': 100.0,
    'cup': '250.0'
}

Другие советы

A simple representation are named tuples. They are okay as long as you do not need an full-blown object-oriented design.

from collections import namedtuple

details = namedtuple('details', 'name sodium amount unit')
food = namedtuple('food', 'details amount unit')
unit = namedtuple('unit', 'name weight')

gram = unit('gram', 1)
slice = unit('slice', 50)
cup = unit('cup', 244)

bread = details(name='bread', sodium=68,  amount=10, unit=gram)
f_bread = food(details=bread, amount=1, unit=slice)

milk = details(name='milk', sodium=98, amount=1, unit=cup)
f_milk = food(details=milk, amount=10, unit=gram)


for f in (f_bread, f_milk):
    total = 1.0 / 1000 * f.amount * f.unit.weight * f.details.sodium / f.details.amount / f.details.unit.weight
    print(
        "%d %s of %s has %0.3f grams sodium" % 
        (f.amount, f.unit.name, f.details.name, total))

Output:

1 slice of bread has 0.340 grams sodium
10 gram of milk has 0.004 grams sodium

I slit up the food details and units from the actual food intake. A kind of bread is probably eaten more than once.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top