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

2

Two natural data m and n determine, among all pairs of natural numbers (x, y) such that x < m e y < n, a pair for which the value of the expression x * y - x ** 2 + y is maximum and also calculate 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 the solution is not very elegant. Any suggestions on how to improve it? Any simpler way?

    
asked by anonymous 22.03.2018 / 23:20

1 answer

4

In fact, your solution has lots of manual work and some language addiction. To facilitate the 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 fully 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 care when the value is zero or negative (let's assume the user knows it should be a positive value).

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

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

The pares object will be a generator that can be iterated to get all possible pairs. Now, for the 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 pares object will generate a two-valued tuple, whereas the f expression will expect two values as a parameter, so we will have to use tuples deconstruction when calling the expression.

Finally, using the function max , we can obtain the pair that has the maximum 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 at Repl.it

    
22.03.2018 / 23:49