How to return an attribute from a class based on the minimum and maximum of other attributes of the array?

Asked

Viewed 70 times

0

Hello, I would like to know how I can go through the vector of objects and return the name of the company that has the smallest amount of employees and the name of the company that has the largest capital.

I know there are the commands min() and max() for the lists. But how to return the name of the company that corresponds to the minimum and maximum value attribute?

class Empresa:
    def __init__(self,nome,capital,nFuncionarios):
        self.nome = nome
        self.capital = capital
        self.nFuncionarios = nFuncionarios

class EmpresaDemo():
    empresa = Empresa(['Teste Corporation','Teste Ltda','Teste & Cia','Teste transportes','Teste Tech'],[1000000,900700,505000,30022,405045],[777,30,40,22,1])
min(empresa.nFuncionarios) # Me retorna apenas o item que possui valor mínimo.
max(empresa.capital) # Me retorna apenas o item que possui valor máximo.

1 answer

0

Your modeling won’t help you much to differentiate one element from the other, they’re all elements within a list, you can use the attribute index() to find out the position of the value you received and find out the other information but the information will remain dissociated.

I would recommend an approach where information is easier to work with:

class Empresa:
    def __init__(self, nome, capital, n_func):
        self.nome = nome
        self.capital = capital
        self.n_func = n_func

    def __str__(self):
        return self.nome


dados_empresas = (
    ("Teste Corporation", 777, 1000000),
    ("Teste Ltda", 30, 900700),
    ("Teste & Cia", 505000, 40),
    ("Teste transportes", 22, 30022),
    ("Teste Tech", 1, 405045),
)

empresas = [Empresa(*i) for i in dados_empresas]

Company data is entered in a list (or array) containing the class you had already defined, getting one object per company (so you have the data all together).

The method __str__() serves to inform the language what you want to be displayed when your class needs to be displayed as string (in case I only display the company name).

So it is possible to use max() and min() directly...

print(max(empresas, key=lambda i: i.capital))
print(min(empresas, key=lambda i: i.n_func))

This "thing" with the lambda serves to pass to the functions the values you want to use to find the maximum and minimum values.

Teste & Cia
Teste & Cia

Browser other questions tagged

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