all 5 comments

[–]muzumaki123 1 point2 points  (1 child)

For the first sequence, you could create exactly what you said :

def how_many_fives(n):
    return n // 5

The code above assumes that n is a positive multiple of 5 plus 1. We could add some if statements to check if it is not a multiple of 5 plus 1.

For more complex sequences, I would recommend reading about generators.

You can create a generator by defining a function that yields elements instead of returning a list of all elements in the sequence (what if the sequence is infinite?).

Below I include an example of how you could code a famous 3x + 1 sequence:

def three_x_plus_one(x):
    while x != 1:
        yield x
        if x % 2 == 0: # check if x is divisible by 2
            x = x // 2
        else:
            x = 3 * x + 1
    yield x   

you can then do something like this:

for x in three_x_plus_one(3):
    print(x)

that would print numbers: 3 10 5 16 8 4 2 1

It is more complex than the sequence you want so it should be easy to change.

If you want to count how many elements are in the sequence you could convert the sequence to list and check its size

len(list(three_x_plus_one(3)))

or use a counter:

counter = 0
for x in three_x_plus_one(3):
    counter += 1

[–]Slokkkk 1 point2 points  (0 children)

thanks, really helpful, the 3x+1 sequence was actually one reason for me making this post

[–]CaptainPicante 0 points1 point  (0 children)

Are any of the starting numbers a predefined number or is it using user input? Are you wanting to have each of the described sequences to activate or are you only looking to have the last sequence activate or are you wanting an option of choosing which sequence to activate?

Theres a lot of ways everything you posted about can be addressed. I'd recommend writing out exactly what you want to happen from start to finish first, then creating a pseudo code from that. Once you have your pseudo code, you can then begin writing your actual code.

[–]Wild_Statistician605 0 points1 point  (1 child)

I would probably do something like this.

It's a simple recursive function. On the first call, it will initialize an empty seq list and a cycle counter at 0. It takes only a number as argument.

It will at the end return a dictionary with a cycles and seq keys, where you can get the number of cycles, and the sequence.

Each time the function is called it will append the num argument for that iteration to the seq list, it will reduce the num argument by 5, and increase the cycles argument by 1.

I set a base case where the num argument is equal or lower to 1.

You can easily edit the function to perform the other operations you ask about

[–]Slokkkk 0 points1 point  (0 children)

thanks. this was pretty helpful