- sushrit_lawliet ( @sushrit_lawliet@lemmy.one ) 5•1 year ago
I remember trying to apply all my understanding of control flow statements back when I first started python to build something similar. That was definitely inefficient, but boy was I proud of it and it’s complex magnificence.
- Elbullazul ( @Elbullazul@lemmy.ml ) 3•1 year ago
The lack of spaces around the math operators is mildly irritating
- brie ( @brie@beehaw.org ) 2•1 year ago
That’s actually pretty good for a beginner.
Some tips (take with a grain of salt since some are just personal preference):
Make collatz take a number, and parse the number outside the loop, which also avoids needing to repeat the conversion to int. It also means that you can remove the try-catch from inside collatz, since the only place a ValueError is expected is the conversion to int.
def collatz(number): ... number = None # Declare number to give it the correct scope while True: try: number = int(input('Type in a positive integer: ')) break except ValueError: print("Input could not be parsed") print(collatz(number))
Avoid commenting what your code does, and instead focus on getting across the intent, like how you commented that
int(number) % 2 == 0
is a check for even numbers. It is fine to leave out comments for pieces of code that are truly self explanatory.The elif condition can be replaced with just else, since it will only be run if the if condition is false.
Format with Black, it makes things look nicer without having to deal with manual formatting.
I appreciate the pointers, but I’m definitely not a beginner anymore. This script is like 4 years old lol.
- brie ( @brie@beehaw.org ) 3•1 year ago
Oops. Hopefully it helps others though!
- JPAKx4 ( @JPAKx4@lemmy.sdf.org ) 1•1 year ago
If you end up doing many numbers, you could create a dictionary, where each number points to the next number in the sequence (ex: [32:16, 16:8, 8:4, 4:2, 2:1], where the first number is the key and the second is the value). If the number already exists in the dictionary, then you know it goes to 1, if it doesn’t then add what you just calculated to the dictionary and then continue.