Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
neighbours solution in Clear category for Triangular Islands by l.szyman10
from typing import Set, Iterable
from math import sqrt
def neighbours(x):
level = lambda z: int(sqrt(z-1)+1)
l = level(x)
n = [x + l*2 if l%2 == 0 and x%2 == 0 or l%2 == 1 and x%2 == 1 else x - (l-1)*2] \
+ [i for i in [x+1, x-1] if x-1 > 0 and level(i) == l]
return n
def triangular_islands(triangles: Set[int]) -> Iterable[int]:
areas, island = [], []
while triangles:
to_check = [triangles.pop()]
while to_check:
new = to_check.pop(0)
for i in neighbours(new):
if i in triangles:
to_check.append(i)
triangles.remove(i)
island.append(new)
areas.append(len(island))
island.clear()
return areas
if __name__ == '__main__':
print("Example:")
print(sorted(triangular_islands({1})))
# These "asserts" are used for self-checking and not for an auto-testing
assert sorted(triangular_islands({1})) == [1]
assert sorted(triangular_islands({2, 3, 6})) == [3]
assert sorted(triangular_islands({4, 3})) == [2]
assert sorted(triangular_islands({1, 4, 7, 8})) == [1, 3]
assert sorted(triangular_islands({1, 2, 3, 4, 5, 6, 7, 8, 9})) == [9]
assert sorted(triangular_islands({1, 2, 4, 5, 7, 9})) == [1, 1, 1, 1, 1, 1]
print("Coding complete? Click 'Check' to earn cool rewards!")
Aug. 30, 2020
Comments: