Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Blobby solution in Uncategorized category for Calculate Islands by Anne29
# Yay! Blob counting! I can count blobs.
# Take a matrix, add 0's around it.
def pad(m):
new_len = len(m[0]) + 2
result = [ [0 for i in range(new_len)] ]
for row in m:
result.append( [0] + row + [0])
result.append([0 for i in range(new_len)])
return result
# mark all the adjacent 1's with '*'
def mark(world, row, col):
if world[row][col] == 1:
world[row][col] = '*'
for delta_r in range(-1, 2):
for delta_c in range(-1, 2):
if world[row + delta_r][col + delta_c] == 1:
mark(world, row + delta_r, col + delta_c)
# Change marks to 0 and count 'em
def count_marks(m):
count = 0
for row in range(len(m)):
for col in range(len(m[0])):
if m[row][col] == '*':
count += 1
m[row][col] = 0
return count
def checkio(data):
# Okey dokey. Do we want to handle special cases at the edges?
# No, we do not. So do away with special cases by surrounding the
# world with water.
world = pad(data)
counts = []
changed = True
while changed:
changed = False
for row in range(len(world)):
for col in range(len(world[0])):
if world[row][col] == 1:
changed = True
mark(world, row, col)
counts.append(count_marks(world))
return sorted(counts)
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio([[0, 0, 0, 0, 0],
[0, 0, 1, 1, 0],
[0, 0, 0, 1, 0],
[0, 1, 0, 0, 0],
[0, 0, 0, 0, 0]]) == [1, 3], "1st example"
assert checkio([[0, 0, 0, 0, 0],
[0, 0, 1, 1, 0],
[0, 0, 0, 1, 0],
[0, 1, 1, 0, 0]]) == [5], "2nd example"
assert checkio([[0, 0, 0, 0, 0, 0],
[1, 0, 0, 1, 1, 1],
[1, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0]]) == [2, 3, 3, 4], "3rd example"
Nov. 8, 2013
Comments: