Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Calculate Islands by minto
def checkio(liste):
taille_island = []
hauteur = len(liste[0])
largeur = len(liste)
island = [[0 for i in range(hauteur+2)]] + [[0] + column + [0] for column in liste] + [[0 for i in range(hauteur+2)]]
for i in range(1,largeur+1):
for j in range (1,hauteur+1):
if(island[i][j]==1):
somme = 0
new_island, somme = count_recursively(i,j,island,somme) # get the area of island
taille_island.append(somme)
return sorted(taille_island) # sort the areas
def count_recursively(i,j,island,somme):
neighbour_1 = [] # list the neighbour of (i,j) equal to 1
island[i][j] = 0
for k in range(i-1,i+2):
for l in range(j-1,j+2):
if(island[k][l]==1):
neighbour_1.append((k,l))
island[k][l] = 0 # put all of them to 0 before counting recursively
for neighbour in neighbour_1:
island, somme = count_recursively(neighbour[0],neighbour[1],island,somme)
return island, 1+somme
#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"
June 8, 2015
Comments: