Created
June 3, 2021 17:53
-
-
Save vidakDK/2f596e11e227f5480889008e577e6b1d to your computer and use it in GitHub Desktop.
Length of n-th look-and-say number
This file contains 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
""" | |
Script to calculate 'look-and-say' sequence numbers | |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | |
Started off with good old `for` loops but wanted to have fun with some | |
functional programming recipes and play some code golf :) | |
""" | |
import functools as _ft | |
import itertools as _it | |
def _next(val: str) -> str: | |
""" Calculate the next 'look-and-say' number. """ | |
return "".join([f"{len(list(group))}{key}" | |
for key, group in _it.groupby(val)]) | |
def length(seed: str, index: int) -> int: | |
""" | |
Calculate the length of a specific number of the 'look-and-say' sequence. | |
Args: | |
seed: Value of the initial number in the sequence. | |
index: Index of the desired number in the sequence. | |
Returns: | |
Length of the number at index `index`, given initial value of `seed`. | |
""" | |
return len(_ft.reduce(lambda x, _: _next(x), range(index - 1), seed)) | |
if __name__ == '__main__': | |
print(length('1', 30)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment