Search code examples
python-2.7smoothing

How to smooth numbers from a file as many times as wanted in Python 2.7?


I'm trying to create a code that will open a file with a list of numbers in it and then take those numbers and smooth them as many times as the user wants. I have it opening and reading the file, but it will not transpose the numbers. In this format it gives this error: TypeError: unsupported operand type(s) for /: 'str' and 'float'. I also need to figure out how to make it transpose the numbers the amount of times the user asks it to. The list of numbers I used in my .txt file is [3, 8, 5, 7, 1].

Here is exactly what I am trying to get it to do:

Ask the user for a filename

Read all floating point data from file into a list

Ask the user how many smoothing passes to make

Display smoothed results with two decimal places

Use functions where appropriate

Algorithm: Never change the first or last value Compute new values for all other values by averaging the value with its two neighbors

Here is what I have so far:

filename = raw_input('What is the filename?: ')
inFile = open(filename)
data = inFile.read()
print data
data2 = data[:]
print data2
data2[1]=(data[0]+data[1]+data[2])/3.0
print data2
data2[2]=(data[1]+data[2]+data[3])/3.0
print data2
data2[3]=(data[2]+data[3]+data[4])/3.0
print data2

Solution

  • You almost certainly don't want to be manually indexing the list items. Instead, use a loop:

    data2 = data[:]
    for i in range(1, len(data)-1):
        data2[i] = sum(data[i-1:i+2])/3.0
    data = data2
    

    You can then put that code inside another loop, so that you smooth repeatedly:

    smooth_steps = int(raw_input("How many times do you want to smooth the data?"))
    for _ in range(smooth_steps):
        # code from above goes here
    

    Note that my code above assumes that you have read numeric values into the data list. However, the code you've shown doesn't do this. You simply use data = inFile.read() which means data is a string. You need to actually parse your file in some way to get a list of numbers.

    In your immediate example, where the file contains a Python formatted list literal, you could use eval (or ast.literal_eval if you wanted to be a bit safer). But if this data is going to be used by any other program, you'll probably want a more widely supported format, like CSV, JSON or YAML (all of which have parsers available in Python).