How to do operation on list of numbers?

Issue

I’m trying to do the Collatz conjecture on a list of numbers to check which one is "holding" the most. the problem is the code keeps telling me "TypeError: unsupported operand type(s) for %: ‘list’ and ‘int’"

Collatz = range(1, 1001)
counting = 0
print(Collatz)
while Collatz != 1:
    if Collatz % 2 == 0:
        Collatz = int(Collatz / 2)
        print(Collatz)
        counting += 1
    else:
        Collatz = int(Collatz * 3 + 1)
        print(Collatz)
        counting += 1
print(counting)

if it’s with input it works great…
Would appreciate help 🙂

try to get a list of all of the ranges, with a number and how long it took to get to "1" or just which one is the longest.
for example:
number 1 took 1 steps to get to "1"
number 2 took 2 steps to get to "1"
number 3 took 8 steps to get to "1" etc

or

number 153 took 736 steps to get to "1" (IDK, just for the example)

Solution

This code will work:

def get_collatz(n):
    i=1
    while True:
        if n % 2 == 0:
            n /= 2
        else:
            n = 3 * n + 1
        if n == 1:
            return(i)
        i += 1
        
for i in range(1, 100000):
    print(i, get_collatz(i))

If you want to know the number that took most steps, you can do this:

steps = dict()
for i in range(1, 100000):
    steps[i] = get_collatz(i)

n_max = max(steps, key=steps.get)
total_steps = steps[n_max]
print(f'Number {n_max} took {total_steps} steps to reach 1.')

This prints:

Number 77031 took 350 steps to reach 1.

You can also create a sorted dictionary:

sorted_steps = dict(sorted(steps.items(), key=lambda item: item[1]))

Answered By – LeonardoVaz

Answer Checked By – Willingham (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.