n00bprogrammer22 - 1 year ago 70
Python Question

Counting values "in a row" in list of lists vertically or horizontally

I'm writing a function that counts the number of occurrences of a specific value of a list of lists in a row whether horizontal or vertical. Then it just needs to return the value of how many times it occurred. Here's an example

``````lst=[['.','.','.','e'],
['A','A','.','e'],
['.','.','.','e'],
['.','X','X','X'],
['.','.','.','.'],
['.','.','.','e']]
``````

For this list of lists, the function should return 3 for e as it appears 3 times in a row, 2 for A, and 3 for X. Thank you for your time

My code so far:

``````def length_of_row(symbol,lot):
count = 0
for sublist in lot:
for x in sublist:
if x == symbol:
count += 1
continue
else:
continue
return count
``````

You can try the following if you don't mind changing things a little bit:

``````from functools import reduce
from itertools import takewhile

def length_of_row(symbol, lot):
if symbol not in reduce(lambda x,y: x+y, lot):
return 0
elif symbol in lot[0]:
good_lot =  map(lambda y: y.count(symbol),takewhile(lambda x: symbol in x, lot))
return sum(good_lot)
else:
return length_of_row(symbol, lot[1:])
``````

This uses a combination of recursion and one of python's powerful `itertools` methods (`takewhile`). The idea is to count the number of symbols until you hit a list that does not contain that symbol. Also, it tries to make sure that it only counts the occurrences of the symbol if said symbol is in the list of lists.

Using it:

``````lst = [['.', '.', '.', 'e'],
['A', 'A', '.', 'e'],
['.', '.', '.', 'e'],
['.', 'X', 'X', 'X'],
['.', '.', '.', '.'],
['.', '.', '.', 'e']]

print(length_of_row('e', lst))
print(length_of_row('X', lst))
print(length_of_row('A', lst))
print(length_of_row('f', lst))

#3
#3
#2
#0
``````

As you can see, if the symbol does not exist it returns `0`.

I hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download