Skip to content

Instantly share code, notes, and snippets.

@vitalizzare
Created January 15, 2022 15:19
Show Gist options
  • Select an option

  • Save vitalizzare/1b7b1575e1488f72969956438f4c8a20 to your computer and use it in GitHub Desktop.

Select an option

Save vitalizzare/1b7b1575e1488f72969956438f4c8a20 to your computer and use it in GitHub Desktop.
Return the maximum height of a continuous sequence of true values in a 2D array, starting from the bottom
import numpy
def get_max_height(skyline:numpy.ndarray) -> int:
'''Returns the maximum height of a continuous sequence
of true values in a 2D array, starting from the bottom'''
mask = True
return sum(any(mask := row & mask)
for row in reversed(skyline.astype(bool)))
def picture(skyline:numpy.ndarray, SEP=' '):
STONE = "\N{LARGE GREEN SQUARE}"
BIRD = "\N{LARGE RED SQUARE}"
SKY = "\N{LARGE BLUE SQUARE}"
image, stones = [], True # stones is also a mask to trace a continuous line of true values
for row in reversed(skyline.astype(bool)):
# stones = row AND mask
# birds = row XOR stones
# mask = stones
birds = row ^ (stones := row & stones)
image.append(SEP.join(
STONE if is_stone else BIRD if is_bird else SKY
for is_stone, is_bird in zip(stones, birds)))
print(*reversed(image), sep='\n')
picture(skyline := numpy.array([
[1, 1, 0, 0],
[0, 0, 1, 1],
[1, 1, 1, 0],
[0, 1, 0, 1],
[1, 1, 0, 1],
]))
print(f'{get_max_height(skyline) = }')
@vitalizzare
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment