Search code examples
pythonarraysdynamic-arrays

Python looping and appending arrays


I'm creating an application to test how many 'steps' it takes for a number to reach 1 using the colatz conjecture. Here is the code:

import sys
import csv

def findSteps(mode):
    count = 0
    while mode != 1:
        count = count + 1
        if mode%2 == 0:
            mode = mode/2
        else:
            mode = (3*mode)+1

    return count

numbers = []
counts = []

for n in range(1, 100):
    important = findSteps(n)
    numbers[n] = n
    counts[n] = important

with open('colatz conjecture table.csv', 'wb') as csvfile:
    myWriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    myWriter.writerow(numbers)
    myWriter.writerow(counts)

Unfortunately, whenever I run it, it gives me a "Index Error: List Assignment out of range."


Solution

  • In addition of the list.append() variant, you may also use

    numbers = range(1, 100)
    counts = [findSteps(n) for n in numbers]
    

    Or, if you like to keep it functional

    numbers = range(1, 100)
    counts = map(findSteps, numbers)