Question #35898

Given a list listA of numbers, write a program that generates a new list listB with the same number of elements as listA, such that each element in the new list is the average of its neighbors and itself in the original list. For example, if listA = [5, 1, 3, 8, 4], listB = [3.0, 3.0, 4.0, 5.0, 6.0], where the values in listB were computed as follows:
(5 + 1)/2 = 3.0
(5 + 1 + 3)/3 = 3.0
(1 + 3 + 8)/3 = 4.0
(3 + 8 + 4)/3 = 5.0
(8 + 4)/2 = 6.0
listA can be hardcoded at the begining of your program, but the solution should work for other lists as well (in particular if we modify the values of the list, the program should work with the new values).
Sample run:
listA = [5, 1, 3, 8, 4]
listB = [3.0, 3.0, 4.0, 5.0, 6.0]
1

Expert's answer

2013-10-09T11:51:10-0400
listA = [5, 1, 3, 8, 4]
def gen_list(l):
    if not l: # check if the input list is None or empty
        return []
    if len(l) == 1: # check if the input lsit contains only 1 element
        return list(l)
    result = [] # the resulting list
    # Find the average for the first element
    result.append((l[0] + l[1]) / 2.)
    # Find the average value for all list elements
    # located between the first and the last element
    for k in xrange(1, len(l) - 1):
        result.append(sum(l[k - 1:k + 2]) / 3.)
    # Find the average value for the last list element
    result.append((l[-1] + l[-2]) / 2.)
    return result
print listA
print gen_list(listA)

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!
LATEST TUTORIALS
APPROVED BY CLIENTS