Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

max collatz sequence python 3

I am trying to solve a problem where recursion is a must. The tasks is: Write a function that takes in an integer n and returns the highest integer in the corresponding Collatz sequence.

My solution is this:

collatz = []

def max_collatz(num):
    collatz.append(num)

    if num == 1:
        return max(collatz)
    else:
        return max_collatz(num / 2) if num%2 == 0 else max_collatz((3 * num) + 1)

However, I need to find a way to solve it without using a list outside of the function. I really couldn’t find a solution, is there any?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s either the current number or the largest in the rest of the sequence.

def max_collatz(n):
    if n == 1:
        return 1
    elif n % 2:
        return max_collatz(3 * n + 1)
    else:
        return max(n, max_collatz(n // 2))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading