-3

My idea is to run the 3n + 1 process (Collatz conjecture) on numbers ending in 1, 3, 7, and 9, within any arbitrary range, and to tell the code to send the lengths of each action to a list, so I can run functions on that list separately.

What I have so far is to specify unit digits 1,3,7 and 9 as: if n % 10 == 1; if n % 10 == 3 ...etc, and I think my plan needs some form of nested for loops; where I'm at with list appending is to have temp = [] and leng = [] and find a way for the code to automatically temp.clear() before each input to leng. I'm assuming there's different ways to do this, and I'm open to any ideas.

leng = []
temp = []
def col(n):
    while n != 1:
        print(n)
        temp.append(n)
        if n % 2 == 0:
            n = n // 2
        else:
            n = n * 3 + 1
    temp.append(n)
    print(n)
martineau
  • 119,623
  • 25
  • 170
  • 301
Russ wB
  • 3
  • 2

1 Answers1

0

It's unclear what specifically you're asking about and want to know, so this is only a guess. Since you only want to know the lengths of the sequences, there's no need to actually save the numbers in each one—which means there's only one list created.

def collatz(n):
    """ Return length of Collatz sequence beginning with positive integer "n".
    """
    count = 0
    while n != 1:
        n = n // 2 if n % 2 == 0 else n*3 + 1
        count += 1
    return count

def process_range(start, stop):
    """ Return list of results of calling the collatz function to the all the
        numbers in the closed interval [start...stop] that end with a digit
        in the set {1, 3, 7, or 9}.
    """
    return [collatz(n) for n in range(start, stop+1) if n % 10 in {1, 3, 7, 9}]

print(process_range(1, 42))

Output:

[0, 7, 16, 19, 14, 9, 12, 20, 7, 15, 111, 18, 106, 26, 21, 34, 109]
martineau
  • 119,623
  • 25
  • 170
  • 301
  • That's exactly what I was looking for, I didn't know what this sort of code looks like when it works, and I couldn't find it anywhere else. – Russ wB Oct 24 '17 at 23:22