Help with Python function

Asked

Viewed 125 times

0

I am currently "developing" a software in python and I have a question about how I can optimize it. My question is the following, I have to calculate grades according to age and rates, Example: One ran 2km and is 30 years old, his grade will be x, however, if another person runs 2km and is 19 years old, his grade will be Y. I am currently doing with if/Elif.

if idade == 19 and corrida == 2000:
     print('Sua nota foi: Ruim.')
elif idade == 30 and corrida == 2000:
     print('Sua nota foi: Muito boa.')

I would like to know if it has any function that cuts several lines of code, because there are several other activities and age 18 to 60 years. Thanks for your help!!!

  • Which the criterion for the note to be good or bad based on age and the amount of km one ran?

  • there is a table (already established), the younger the age, the more Oce needs to run, do pushups, sit-ups and bars, however, at the ages of 20 to 22 these indices increase a little, and from the 23 repeat the Index of 18.

  • Have you tried to fit this data, excluding the data that presents these exceptions?

1 answer

0


If you’re always going to compare values exact age and year, the simplest solution is to use a dictionary, where the keys are the values you want to compare, in the form of a tuple (simply separate the values by ,):

tabela = {
   (19, 2000): "Ruim",
   (30, 2000): "Muito boa",
}

print (f"Sua nota foi {tabela[idade, corrida]}.")

How are you likely to have several "notes" that will repeat themselves to stripes of age and meters - (for example, the note will be "bad" for age "19" to "25" and race from "1500" to "2500"), it is not feasible, even in the form of dictionary, you have 1000 entries with running footage for each age = 10000 items in the dictionary only for the bad note.

In this case, the most efficient way would be something similar to a dictionary, but with an internal "tree" structure that would allow locating a given value if it is between two other values- and the key would have only these two values. Python doesn’t have such a data structure by default, and developing one can be a bit tricky. It would not be difficult to find libraries with this ready - but there enter several other factors.

But, given that you will not have so many keys so, it is worth another strategy: A dictionary with the keys, as above, but only with the lower values of each entry in the table, and a list (actually two, one for "age" and one for "race", where each item is this lower value - thus, given the variables "input" and "race", instead of using these values directly in the dictionary, you scroll through the list, and, when you find a value greater than the data that you has, you take the value previous and uses this to get your final data in the dictionary:

tabela = {
   (0, 2000): "Muito jovem pra correr",
   (18, 2000): "Ruim",
   (25, 2000): "Muito boa",
   # não escapa de repetir os valores para cada faixa de metros, por exemplo:
   (0, 4000): "Muito jovem pra correr",
   (19, 4000): "Boa",
   (25, 4000): "Super homem",
}

faixas_idade = [0, 18, 25, 1000000]
faixas_corrida = [2000, 4000, 1000000]

def obtem_inicio_faixa(faixa, valor):
    for item in faixa:
        if valor < item:
            return item_anterior
        item_anterior = item

    raise ValueError("Valor fora das faixas definidas")

def obtem_nota(idade, corrida):
     idade_base = obtem_inicio_faixa(faixas_idade, idade)
     corrida_base = obtem_inicio_faixa(faixas_corrida, corrida)
     return tabela[idade_base, corrida_base]

...
print(f"Sua nota foi: {obtem_nota(idade, corrida)}")

This is a realistic code, without much worry about optimization (due to linear searches), but that would still be well performed for a maximum of 300 to 500 tracks in each of the variables. (this for a web application, having to answer dozens of times this note in a single second - for a single-user application, with print and input, this would handle 100000 tracks easily). For a web application of hundreds of requests per second, or many more tracks, it would be worth developing the tree structure I mentioned earlier.

As you’re learning, it’s important to look at two things in this code: the use of functions to organize algorithms - even in this simple case, I have a function that’s used for two different types of data and the code is re-used. The second thing is that you should not mix input and output with logic: the code that prints the results never will stay within the functions that contain program logic - these functions only locate the value. The "communication" with the user is on account of another part of the program, specific to this (in this case, a "print" outside the functions, but in a larger application, and specific functions to print values - in Web applications, are the functions of "view", for example).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.