Created
January 15, 2022 15:19
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) = }') |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://twitter.com/gusthema/status/1482340641178857473