Home > OS >  TypeError cannot unpack non-iterable float object in centered average algorithm Python
TypeError cannot unpack non-iterable float object in centered average algorithm Python

Time:03-07

I have a Type Error from centered average algorithm in Python. this is my code

def calc_centered_average(numbers):
    sorted_list = sorted(numbers)
    return sum(sorted_list[1:-1])/(len(numbers)-2)
    # return subnumbers, centered_average


numbers = [1, 4, 5, 6, 100]
sublist, cavg = calc_centered_average(numbers)
print(f"The centered average of {numbers} is {cavg} (based on {sublist}).")

CodePudding user response:

Your problem is caused because you are returning one value instead of two in your function. Here is the correct way that I assume you should do it:

def calc_centered_average(numbers):
    sorted_list = sorted(numbers)
    subnumbers = sorted_list[1:-1]
    centered_average = sum(subnumbers)/(len(numbers)-2)
    return subnumbers, centered_average


numbers = [1, 4, 5, 6, 100]
sublist, cavg = calc_centered_average(numbers)
print(f"The centered average of {numbers} is {cavg} (based on {sublist}).")
  • Related