Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function does not output correct maximum value

I would like to find the maximum value z and find its i and j values at z maximum.

I tried the code using def function and did not get the correct maximum z value and its i and j values.

Below is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

maxi = 0
def i_j ():
    global maxi
    for i in range (1, 5):
        for j in range (1, 5):
            z = i + j
            print(z)
            if z > maxi:
                maxi = z
                return i, j
            j += 1
        i += 1
print ("Maximum: {}".format(maxi))
x, y = i_j()
print ("i at max:", x)
print ("j at max:", y)

The output of the Python code:

Maximum: 0
2
i at max: 1
j at max: 1

Kindly help me, many thanks.

>Solution :

You are returning too early, this means you leave the function the first time that z>maxi is true, which means in the very first iteration.

Also, there are other mistakes that commenters pointed out:

  • maxi doesn’t make much sense to print before calling the function
  • the for loop automatically increases the loop variables (or rather, iterates through the list that is range(1,5,1) and thus the incrementation doesn’t actually do anything because it gets overwritten in the next step)

This is how it should look:

def i_j ():
    maxi = 0
    maxi_i = 0
    maxi_j = 0
    for i in range (1, 5, 1):
        for j in range (1, 5, 1):
            z = i+j
            print ("{}".format(z))
            if z > maxi:
                maxi = z
                maxi_i = i
                maxi_j = j
    return (maxi, maxi_i, maxi_j)

maxi, x, y = i_j ()
print ("Maximum: {}".format(maxi))
print ("i at max: {}".format(x))
print ("j at max: {}".format(y))

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading