0

The following code creates a list with entered values:

def locateLargest():

    matrix = []
    numberOfRows = int(input("Enter the number of rows: "))
    numberOfColumns = 2

    for row in range(0, numberOfRows):
        matrix.append([])
        for column in range(0, numberOfColumns):
            value = int(input("Enter a value: "))
            matrix[row].append(value)


    max_value = None
    for value in matrix:
        if not max_value:
            max_value = value
        elif value > max_value:
            max_value = value
    print(max_value)

locateLargest()

The issue I am running into is that it is asking for each value individual in the row, and is returning the maximum pair of values in the row, not the maximum value's index.

The sample run of what I should be getting is:

Enter the number of rows in the list: 3
Enter a row: 23.5 35 2 10
Enter a row: 4.5 3 45 3.5
Enter a row: 35 44 5.5 11.6
The location of the largest element is at (1,2)

Any ideas?

My current output is:

Enter the number of rows: 2
Enter the number of columns: 6
Enter a value: 2
Enter a value: 2
Enter a value: 2
Enter a value: 2
Enter a value: 2
Enter a value: 2
Enter a value: 7
Enter a value: 6
Enter a value: 4
Enter a value: 3
Enter a value: 6
Enter a value: 2
[7, 6, 4, 3, 6, 2]
1
  • 1
    You are iterating over list of lists, so each value is a list. You need to think about retrieving individual values from each of these lists in order to perform relevant comparison. Commented Nov 21, 2016 at 20:48

2 Answers 2

1

This is not very 'pythonic' but will help you achieve your end goal and hopefully understand the process. As Łukasz mentioned, you need to do an iteration for each row, and for each column in each row:

First declare the variable to store your location:

maxPoint = [0,0]

Then enumerate your matrix such that you can get the list from each row, but also retrieve the index of the currently active row:

for idx, row in enumerate(matrix):

Find the max value in the current list of values, ie: [10, 20, 30]

    maxRowValue = max(row)

Find which column this maximum value lives in, ie: [0, 1, 2, ...]

    maxRowIndex = row.index(maxRowValue)

Determine if max row value is in fact greater than any other previously located points, if it is less discard it:

    if maxRowValue <= matrix[maxPoint[0]][maxPoint[1]]:
            continue

If the value is greater, save it to the maxPoint variable:

    maxPoint = [idx, maxRowIndex]

EDIT

For the sake of completeness, here is the complete code sample with AChampion's performance improvements added:

def locateLargest():

    matrix = []
    numberOfRows = int(input("Enter the number of rows: "))
    numberOfColumns = 2

    for row in range(0, numberOfRows):
        matrix.append([])
        for column in range(0, numberOfColumns):
            value = int(input("Enter a value: "))
            matrix[row].append(value)

    maxPoint = [0,0]

    for rIndex, row in enumerate(matrix):
        cIndex, maxRowValue = max(enumerate(row), key=lambda x: x[1])
        if maxRowValue <= matrix[maxPoint[0]][maxPoint[1]]:
            continue
        maxPoint = [rIndex, cIndex]

    print(maxPoint)

locateLargest()

EDIT 2

Here is the same algorithm without using enumerate:

currentRow = 0

for row in matrix:
    maxRowValue = max(row)
    maxRowIndex = row.index(maxRowValue)
    if maxRowValue > matrix[maxPoint[0]][maxPoint[1]]:
            maxPoint = [currentRow, maxRowIndex]
    currentRow += 1
Sign up to request clarification or add additional context in comments.

5 Comments

This is very interesting, been playing around with it since you posted. The only issue I am running into is that if you end up having 2 values greater then the starting value. It replaces it, but at the end prints both that are larger. For instance: if you enter nothing but 1's and a 12 at the end it prints the index of the 12...but if you have a lot of high numbers it prints the highest 2.
It outputs the index coordinates of the max value in the matrix? I don't know what you mean by 'prints both that are larger'
enumerate() is your friend instead of finding the max and then finding the index you can find both, e.g. index, value = max(enumerate(row), key=lambda x: x[1])
Thanks @AChampion, that is definitely an important performance improvement. I was mostly trying to keep concepts simple to explain the logic a little better.
How can I do this without the map/enumerate function? I am still really new to programming in general....and this isn't something I understand fully, so I can't really utilize it.
0

Using enumerate() and some generator expressions, you can reduce this code quite a bit:

  • Generate the rows
  • Generate the maximum for each row
  • Find the maximum across all rows

More complex perhaps than some would like:

numberOfRows = int(input("Enter the number of rows: "))
# Generate the rows
rows = (map(int, input("Enter a row: ").split()) for _ in range(numberOfRows))

# Generate the maximum for each row
max_row = (max(enumerate(data), key=lambda x: x[1]) for data in rows)

# Find the maximum across all rows
i, (j, v) = max(enumerate(max_row), key=lambda x: x[1][1])
print("The location of the largest element is at {} [{}]".format((i, j), v))

Input / Output:

Enter the number of rows: 3
Enter a row: 1 2 3
Enter a row: 3 6 3
Enter a row: 1 2 3
'The location of the largest element is at (1, 1) [6]'

If you want to see what is going on change the generators to list comprehensions:

>>> rows = [list(map(int, input("Enter a row: ").split())) for _ in range(numberOfRows)]
Enter a row: 1 2 3
Enter a row: 3 6 3
Enter a row: 1 2 3
>>> rows
[[1, 2, 3], [3, 6, 3], [1, 2, 3]]
>>> max_row = [max(enumerate(data), key=lambda x: x[1]) for data in rows]
>>> max_row
[(2, 3), (1, 6), (2, 3)]
>>> list(enumerate(max_row))
[(0, (2, 3), (1, (1, 6)), (2, (2, 3))]
              ^^^^^^^^^
              i, (j, v)

5 Comments

Maybe its a python culture thing, but I feel like I would have no idea why I wrote this or what it means in 3 months.
Perhaps it is a little complex, but they are relatively standard idioms in python.
I am not very familiar with the enumerate and map functions. Doing a bit of research on them...lot's to learn :D
Not gonna lie, been looking at this and googling different functions and layouts within the code....and I just can't seem to figure it out (reverse engineering). I've been doing python for about 2 months now (college intro course)...and this seems far out of my league.
How can I do this without the map/enumerate function? I am still really new to programming in general....and this isn't something I understand fully, so I can't really utilize it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.