Alan Wakke Alan Wakke - 1 month ago 5
Python Question

How to check the identity of elements following a certain element in a list?

I'm creating a function to check if a list contains only certain elements to the right of a different certain element and then returning a Boolean. But I'm having trouble figuring out how to get the positioning, how would I go about checking the list properly? Anything right of 'A' has to be

.
in order to be return
True
. If there is another string, it will be return
False
.

Example:

Area0 = [['.', '.', 'A', 'A', '.', '.']]


right_path_clear(Area)
→ True

Area1 = [['.', '.', 'A', 'A', '.', 'e']]


right_path_clear(Area)
→ False

Code I have so far:

def right_path_clear(area):
for i in len(area):
if "A" in area[i] and area == '.':
return True

Answer

In case you do not want to use any extra method, you may create a function like:

def right_path_clear(area):
    for row in area:
        for content in row[::-1]: # iterate in reverse order
            if content == '.':    
                continue     # continue iteration till it receives '.'
            elif content == 'A':
                return True  # apart from '.', if 'A' is encounter first, return True
            else:
                return False  # apart from '.', if first encountered value is other than 'A', return False

Sample run:

# Example 1
>>> Area0   =   [['.',  '.',    'A',    'A',    '.',    '.']]
>>> right_path_clear(Area0)
True

# Example 2
>>> Area1   =   [['.',  '.',    'A',    'A',    '.',    'e']]
>>> right_path_clear(Area1)
False
Comments