warrior4223 - 1 year ago 60
Python Question

# Searching for obstacles in list of lists?

I'm writing a function that when given a list of lists it can determine if a specific first character is followed by a specific second character (either once or repeated) or is followed by another random string. When another random string is present the function should return False but when no random string is present the function should return True.

Basically if any other character other then

`.`
comes after
`B`
in its current list or any following lists then it should return False but if only
`.`
is present then it should return True.

For example, if the first character was
`B`
and the second character was
`.`
and the list of lists was
`[['.','.','B','.'],['.','.','.','.']]`
then it should return
`True`
but if the list of lists was
`[['a','c','B','r'],['.','s','g','h']]`
it should return
`False`
since a series of random strings follows
`B`
.

Any tips or help would be appreciated this is the code I have so far:

``````def free_of_obstacles(lst):
A = 'B'
B = '.'
for i, v in enumerate(lst):
if A in v:
continue
if B in v:
continue
return True
else:
return False
``````

You could join all the chars in each list and join all the joined strings into a single string and then apply a regex to check if there is a match or not:

``````>>> lst=[['.','.','B','.'],['.','.','.','.']]
>>> import re
>>> bool(re.search(r'B(\.+)\$', ''.join(''.join(i) for i in lst)))
True
>>> lst=[['a','c','B','r'],['.','s','g','h']]
>>> bool(re.search(r'B(\.+)\$', ''.join(''.join(i) for i in lst)))
False
>>>
``````

Without using any imported modules:

Sample run 1

``````>>> lst=[['.','.','B','.'],['.','.','.','.']]
>>> newlst=[j for i in lst for j in i]
>>> newlst=newlst[newlst.index('B')+1:]
>>> newlst
['.', '.', '.', '.', '.']
>>> list(map(lambda x:x=='.', newlst))
[True, True, True, True, True]
>>> all(list(map(lambda x:x=='.', newlst)))
True
``````

Sample run 2

``````>>> lst=[['a','c','B','r'],['.','s','g','h']]
>>> newlst=[j for i in lst for j in i]
>>> newlst=newlst[newlst.index('B')+1:]
>>> newlst
['r', '.', 's', 'g', 'h']
>>> list(map(lambda x:x=='.', newlst))
[False, True, False, False, False]
>>> all(list(map(lambda x:x=='.', newlst)))
False
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download