Reputation: 57
I am making a list and I want to test for a positive result of 4 or more in a row in any directions (I am testing for B and E) e.g.:
List = [N, N, B, N, N, E, B, E, N,
N, E, B, N, E, E, E, B, N,
N, N, N, N, N, E, B, E, N,
N, E, B, N, E, E, E, B, N]
It is longer but you get the point,
anyway I would want that to return as True for E
as there are four in a row for E
but no for B
. I also want to test for diagonal as well but I am struggling to work out how to even attempt this as it is.
I have no example code because I don't know how to attack this problem.
Let me know if I need to explain differently.
Upvotes: 0
Views: 123
Reputation: 9858
It is easier if we can represent this data as a grid structure with x, y coordinates for each point. We can use a class to set the data up in this way. The class needs to know how wide you want the grid to be in order to do this. To find a sequence of items, we can iterate through the rows and columns, and each time we find a match for the item, we check that the adjacent squares in each direction also contain the same item.
class Grid(object):
def __init__(self, data, width):
self.data = data
self.width = width
self.height = len(L) / width
def get(self, x, y):
""" Find the item in the grid at the given coordinates """
if 0 <= x < self.width and 0 <= y < self.height:
return self.data[y * self.width + x]
def find_sequence(self, item, times):
""" Check for a sequence of item occuring at least the specified
number of times. Checks right, down, down-right, and down-left. """
for y in range(self.height):
for x in range(self.width):
# if we find the item at x, y...
if self.get(x, y) == item:
# ... then look at adjacent items in each direction
for dx, dy in [(1, 0), (0, 1), (1, 1), (-1, 1)]:
if all(self.get(x + i*dx, y + i*dy) == item
for i in range(1, times)):
return True
return False
N, B, E = "N", "B", "E"
data = [N, N, B, N, N, E, B, E, N,
N, E, B, N, E, E, E, B, N,
N, N, N, N, N, E, B, E, N,
N, E, B, N, E, E, E, B, N]
grid = Grid(data, width=9)
grid.get(3, 3) # N
grid.find_sequence(B, 4) # False
grid.find_sequence(N, 4) # True
grid.find_sequence(E, 4) # True
Upvotes: 1
Reputation: 11
Is this what you are looking for?
List = [N, N, B, N, N, E, B, E, N,
N, E, B, N, E, E, E, B, N,
N, N, N, N, N, E, B, E, N,
N, E, B, N, E, E, E, B, N]
limit = 4
flag = False
oldValue = ''
newValue = ''
counter = 0
for i in range(0, len(List)):
newValue = List[i]
if (newValue == oldValue):
counter += 1
oldValue = newValue
if (counter >= 4):
flag = True
break
print 'Result is' + str(flag)
Upvotes: 0