From b33ea81a7437eaf7d048d92a9b75330c9d9e165e Mon Sep 17 00:00:00 2001 From: Akshay Dubey <38462415+itsAkshayDubey@users.noreply.github.com> Date: Fri, 18 Nov 2022 13:48:47 +0530 Subject: [PATCH] algorithm: Add juggler sequence (#7985) * feat: Add juggler sequence * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * refactor: Remove temp variable * refactor: Change error type for negative numbers * refactor: Remove # doctest: +NORMALIZE_WHITESPACE * refactor: Remove int typecasting * test: Add unit tests for n=10 and n=25 * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- maths/juggler_sequence.py | 61 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 maths/juggler_sequence.py diff --git a/maths/juggler_sequence.py b/maths/juggler_sequence.py new file mode 100644 index 000000000..9daba8bc0 --- /dev/null +++ b/maths/juggler_sequence.py @@ -0,0 +1,61 @@ +""" +== Juggler Sequence == +Juggler sequence start with any positive integer n. The next term is +obtained as follows: + If n term is even, the next term is floor value of square root of n . + If n is odd, the next term is floor value of 3 time the square root of n. + +https://en.wikipedia.org/wiki/Juggler_sequence +""" + +# Author : Akshay Dubey (https://github.com/itsAkshayDubey) +import math + + +def juggler_sequence(number: int) -> list[int]: + """ + >>> juggler_sequence(0) + Traceback (most recent call last): + ... + ValueError: Input value of [number=0] must be a positive integer + >>> juggler_sequence(1) + [1] + >>> juggler_sequence(2) + [2, 1] + >>> juggler_sequence(3) + [3, 5, 11, 36, 6, 2, 1] + >>> juggler_sequence(5) + [5, 11, 36, 6, 2, 1] + >>> juggler_sequence(10) + [10, 3, 5, 11, 36, 6, 2, 1] + >>> juggler_sequence(25) + [25, 125, 1397, 52214, 228, 15, 58, 7, 18, 4, 2, 1] + >>> juggler_sequence(6.0) + Traceback (most recent call last): + ... + TypeError: Input value of [number=6.0] must be an integer + >>> juggler_sequence(-1) + Traceback (most recent call last): + ... + ValueError: Input value of [number=-1] must be a positive integer + """ + if not isinstance(number, int): + raise TypeError(f"Input value of [number={number}] must be an integer") + if number < 1: + raise ValueError(f"Input value of [number={number}] must be a positive integer") + sequence = [number] + while number != 1: + if number % 2 == 0: + number = math.floor(math.sqrt(number)) + else: + number = math.floor( + math.sqrt(number) * math.sqrt(number) * math.sqrt(number) + ) + sequence.append(number) + return sequence + + +if __name__ == "__main__": + import doctest + + doctest.testmod()