0

I'm writing a function that needs to return the row, and column of the last occurrence of a certain character in a list of lists. If the character isn't in the list of lists the function should return None. The function ignores or skips the first occurrences and then returns the row and col of the last occurrence as an ordered pair.

Example: 

lst = [['.','.','.','e'],
       ['A','A','.','e'],
       ['.','.','.','e'],
       ['.','X','X','X'],
       ['.','.','.','.'],
       ['.','y','Z','Z']]

#For this list of lists the function should return (5,3) for Z since it is in the 6th list, 
#and is the 6th value (python starts the count at 0) and for X it should return (3,3)

I think my current code finds the row and column of the first occurrence of a character but not the last occurrence. How could I instruct Python to ignore the first occurrences and instead return the row and col of the last one?

Code:

def get_far_end(symbol,lot):
    for i in range(len(lot)):
        for j in lot[i]:
            if j == symbol:
                return i ,lot[i].index(j)   
n00bprogrammer22
  • 187
  • 5
  • 12
  • 1
    Start from then end and step backwards, the first occurence you find will be the last one in your list. – Knells Nov 01 '16 at 01:45

4 Answers4

1

Start from end and go backwards:

def get_far_end(symbol,lot):
    for i in range(len(lot)-1,-1,-1):
        for j in range(len(lot[i])-1,-1,-1):
            if lot[i][j] == symbol:
                return i ,j
    return None   
Sweeney Todd
  • 880
  • 1
  • 11
  • 25
0

The problem of your algorithm is that you are returning as fas as you find the first occurrence of the element.

So What you should do is, when you find j==symbol save the both index and keep ruuning your matrix

after all loops, you will have the last occurance of your symbol..

Or, a second aproach is, starts from the end, and run the inverse matrix, in this case, you can return the first occurence of j==symbol

0

I assume you are interested in any character, except '.'. If so, then you could do it usign a dictionary as follows:

lst = [['.','.','.','e'],
       ['A','A','.','e'],
       ['.','.','.','e'],
       ['.','X','X','X'],
       ['.','.','.','.'],
       ['.','y','Z','Z']]

out_dict = {}

for i in range(len(lst)):
        for j in range(len(lst[i])):
            if lst[i][j] is not '.':
                out_dict[lst[i][j]] = [i,j]


print(out_dict)
# {'Z': [5, 3], 'y': [5, 1], 'X': [3, 3], 'A': [1, 1], 'e': [2, 3]}
Marcin
  • 215,873
  • 14
  • 235
  • 294
0

If you want position for each character you can do one liner with dict comprehension:

lst = [['.','.','.','e'],
       ['A','A','.','e'],
       ['.','.','.','e'],
       ['.','X','X','X'],
       ['.','.','.','.'],
       ['.','y','Z','Z']]

res = {c: (i, j) for i, sub in enumerate(lst) for j, c in enumerate(sub) if c != '.'}
print(res)

Output:

{'A': (1, 1), 'X': (3, 3), 'Z': (5, 3), 'e': (2, 3), 'y': (5, 1)}
niemmi
  • 17,113
  • 7
  • 35
  • 42