[Python] Collatz Conjecture in Python

Discussão em 'Python' iniciado por Stack, Setembro 26, 2024.

  1. Stack

    Stack Membro Participativo

    I'm relatively new to Python and I decided to try and code a relatively simple collatz conjecture where the user enters a number (integer). The code is just a simple function that calls itself. i is a list that should have every number that the function calculates appended to it. I'm new to executing Python scripts and I have tried using the IDLE shell to run the code. It asks me what number I want but when I enter a number nothing is printed? I'm sure I just need to edit a small bit of this code (or maybe it's all wrong yikes) but does anybody have any idea why my script returns nothing? Sorry about this and thanks. Here's the code:

    l = input("Enter a number: ")
    l = int(l)
    i = []
    def collatz(n):
    if n==1:
    return i
    if n%2 == 0:
    n = n/2
    i.append(n)
    return collatz(n)
    else:
    n = ((n*3) + 1) / 2
    i.append(n)
    return collatz(n)
    print(i)
    collatz(l)

    Continue reading...

Compartilhe esta Página