0

Scenario, a two-dimensional list with any number of rows and columns, and the program returns a list of the row and column indices of the maximum value in the list. Example

print max_position([[2,4],[6,0],[2,6]])

list visualised:

2,6,2
4,0,6

result be [(1,0),(2,1)]

Now, how can I allow the user to enter any rows or columns of two-dimensional list to work for my code?

The code:

def max_position(list2D):
    if not list2D:
        return []
    else:
        maxi = list2D[0][0]
        pos = [] #initialise with no position
        for row in range(len(list2D)):
            for col in range(len(list2D[row])):

                if (list2D[row][col] == maxi):
                    if (row,col) != (0,0):
                        pos.append((row,col))

                elif (list2D[row][col] > maxi): # new maximum found
                    pos = [(row,col)] 
                    maxi = list2D[row][col]

        return pos
Georgy
  • 12,464
  • 7
  • 65
  • 73
zenoh
  • 2,071
  • 1
  • 22
  • 38

3 Answers3

3
import ast
data = raw_input("Enter your 2D array in the form [[], []]:")
x = ast.literal_eval(data)

# in
[[1,2],[3,4],[5,6]]

# out
x
[[1, 2], [3, 4], [5, 6]]

type(x)
<type 'list'>

This does not do much in the way of error handling, they must enter a syntactically correct 2D array, but it'll do the trick.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • Cool! According to the docs, _"This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself"_, so it seems to be the perfect solution. – José Tomás Tocino May 19 '14 at 17:28
1

How about something like this. This would let you enter in one line at a time each sublist and add it to the overall list.

mylist = []

done = False
while not done: 
    line = raw_input()
    if line != '': 
        mylist += [line.split(',')]
    else:
        done = True

print mylist
woot
  • 7,406
  • 2
  • 36
  • 55
0
print "Enter space seperated values, or leave blank to finish"
print list(iter(lambda : map(int,raw_input().split()),[]))

is a fun way to do it :P

of coarse it like the other answers does not actually locate the indices in the resulting array

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179