Home > Enterprise >  How to Compare specific elements in 2D array in python
How to Compare specific elements in 2D array in python

Time:05-21

Hello Im trying to Compare these specific elements to find the highest number : Q_2 = [[5,0,41],[6,3,5],[7,4,3],[8,5,40]] This is my 2d array in python i want to compare Q_2[i][2] with each other the example is that number 41 gets compared to 5 and 3 and 40 and the result is the highest number I came with 2 ways I store the Q_2[i][2] of the every item to a new list (which i dont know why it wont) or do a loop to compare them

from array import *
#These 2 are used to define columns and rows in  for other 2d arrays (All arrays have same column and row)
n = int(3)
m = int(input("Enter Number of Proccess \n")) #I always type 4 for this variable
Q_2 = [[5,0,41],[6,3,5],[7,4,3],[8,5,40]]
for i in range(m):
    for j in range(1,3,1):
       if(Q_2[i][2]>=Q_2[j][2]:
               Max_Timers = Q_2[i]
print(Max_Timers) #to check if the true value is returned or not

The result it returns is 40 This worked when the 0 index was lower then others but once i changed the first one to 41 it no longer works

CodePudding user response:

there is no need of two 'for' loops, as your are after just one element from a 2D array rather than complete 1D array.

This is a working code on 2D array, to get the 1D array that got the highest element on index-2:

max_index = 0
Q_2 = [[5,0,41],[6,3,5],[7,4,3],[8,5,40]]
for i in range(len(Q_2)):
    if(Q_2[i][2]>=Q_2[max_index][2]):
        max_index = i
print(Q_2[max_index])

CodePudding user response:

The reason your code doesn't work can be easily found out by working out a dry run using the values you are using.

According to your logic,

number 41 gets compared to 5 and 3 and 40 and the result is the highest number

and this is achieved by the two for loops with i and j. But what you overlooked was that the max-value that you calculated was just between the current values and so, you are saving the max value for the current iteration only. So, instead of the Global maximum, only the local/current maximum was being stored.

A quick dry-run of your code (I modified a few lines for the dry-run but with no change in logic) will work like this:

41 is compared to 5 (Max_Timers = 41)
41 is compared to 3 (Max_Timers = 41)


5 is compared to 3 (Max_Timers = 5)


40 is compared to 5 (Max_Timers = 40)
40 is compared to 3 (Max_Timers = 40)

>>> print(Max_timers)
40

So, this is the reason you are getting 40 as a result.

The solution to this is perfectly mentioned by @Rajani B's post, which depicts a global comparison by storing the max value and using that itself for comparison.

Note: I didn't mention this above but even when you used a 2nd for loop, which was already not required, there was an even less reason for you to use a range(1,3,1) in the 2nd loop. As you can see in the dry-run, this resulted in skipping a few of the checks that you probably intended.

  • Related