Calculation of the maximum value for an expression of natural numbers using Python

Asked

Viewed 507 times

1

Natural data m and n determine, among all pairs of natural numbers (x,y) such that x < m and y < n, a pair for which the value of the expression x*y - x**2 + y is maximum and also calculates this maximum.

I solved the problem like this:

m = int(input("Digite m: "))

n = int(input("Digite n: "))

#m = 2
#n =1
x = 0
y = 0
maximo =0
x_maximo = 0
y_maximo = 0
while x <m and y<n:
    for i in range(m):
        for j in range(n):

            soma = i*j -i**2 +j
            print (soma)
            if soma > maximo:
                maximo = soma
                x_maximo = i
                y_maximo = j
    x +=1
    y +=1
print ("O máximo é {} para o par (x,y) = ({},{})". format(maximo,x_maximo,y_maximo))

Apparently, the algorithm is correct but I found that the solution is not very elegant. Any suggestions on how to improve it? Some simpler way?

1 answer

4


In fact its solution has a lot of manual work and some language addictions. To facilitate understanding, let’s start by reading the values of m and n:

m = int(input('m:'))
n = int(input('n:'))

In this way, we ask the user for the values, but we do not completely treat the value. When converting to integer, we have that if the input is not an integer value an exception will be raised, but we do not worry when the value is zero or negative (let’s assume that the user knows that it should be a positive value).

To draw up all pairs of natural numbers (x, y) such that x < m and y < n, we can use the function itertools.product together with the function range:

pares = product(range(m), range(n))

The object pares will be a generator that can be iterated to get all possible pairs. Already, for mathematical expression, we can use a lambda:

f = lambda x, y: x*y - x**2 + y

The only detail to be taken care of here is that our object pares will generate a tuple of two values, while the expression f wait two values as parameter, then we will have to use the deconstruction of tuples when calling the expression.

Finally, using the function max, we can get the pair that has the most in the expression:

par = max(pares, key=lambda par: f(*par))

And, displaying the results:

print('Par:', par)
print('Máximo:', f(*par))

The final code would look something like:

from itertools import product

f = lambda x, y: x*y - x**2 + y

m = int(input("m: "))
n = int(input("n: "))

pares = product(range(m), range(n))

par = max(pares, key=lambda par: f(*par))

print('Par:', par)
print('Máximo:', f(*par))

See working on Repl.it

  • What would be lambda?

  • 1

    @Eds conceptually, the expression lambda "is" an "anonymous" function that transforms an input A into an output B.

Browser other questions tagged

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