########################################################################### # Ex
ID: 3607563 • Letter: #
Question
###########################################################################
# Exercise 3
###########################################################################
# A list of numbers can be very unsmooth, meaning very high numbers
# can be right next to very low numbers. This list may represent a smooth path
# in reality that is masked with random noise
# (for example, satellite trajectories with inaccurate transmission).
# One way to smooth the values in the list is to replace each value with
# the average of each value's neighbors, including the value itself.
###########################################################################
# Exercise 3A
# * Write a function moving_window_average(x, n_neighbors) that takes a list x
# and the number of neighbors n_neighbors on either side of a given member
# of the list to consider.
# * For each value in x, moving_window_average(x, n_neighbors) computes the average
# of that value's neighbors, where neighbors includes the value itself.
# * moving_window_average should return a list of averaged values that is the same
# length as the original list.
# * If there are not enough neighbors (for cases near the edge),
# substitute the original value as many times as there are missing neighbors.
# * Use your function to find the moving window sum of x=[0,10,5,3,1,5]
# and n_neighbors=1.culate.
import random
random.seed(1)
def moving_window_average(x, n_neighbors=1):
n = len(x)
width = n_neighbors*2 + 1
x = [x[0]]*n_neighbors + x + [x[-1]]*n_neighbors
# To complete the function,
# return a list of the mean of values from i to i+width for all values i from 0 to n-1
# more your code goes here!
# Exercise 3B
# * Compute and store R=1000 random values from the interval (0, 1) as x.
# * Compute the moving window average for x for values of n_neighbors ranging from 1 to 9 inclusive.
# * Store x as well as each of these averages as consecutive lists in a list called Y (letter is captal)
# write your code here!
# Exercise 3C
# * For each list in Y, calculate and store the range (the maximum minus the minimum)
# in a new list ranges.
# * Print your answer. As the window width increases,
# does the range of each list increase or decrease? Why do you think that is?
# write your code here!
use python for all part!
Explanation / Answer
Python code for function:
def moving_window_average(x,n_neighbours):
i = 0
length = len(x)
result = [None]*length
while (i < length):
sum1 = 0
counter = i
n = n_neighbours
while n > 0:
sum1 = sum1 + x[counter]
n = n-1
counter = counter + 1
if(counter == length):
break
sum1 = sum1 + x[i]*n
average = sum1/n_neighbours
result[i] = average
i= i + 1
return result
For part B
from random import *
for i in 1:1000
x = randint(0,1)
pass in function
Thank You
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.