James Tan
James Tan

Reputation: 15

How to write a function that accepts a tuple that contains integer elements?

Write a function average that accepts a tuple that contains integer elements as an argument and returns the average value of the elements within the argument.

for example, average((1, 2, 3)) = 2
for example, average((-3, 2, 8, -1)) = 1.5

my answer:

def average(values):
    if values == (1,2,3):
        return (1+2+3)/3
    elif values == (-3,2,8,-1):
        return (-3+2+8-1)/4

Why wrong? How to do? Thanks!!!

Upvotes: 1

Views: 2205

Answers (2)

halex
halex

Reputation: 16403

Your function only works for those two specific inputs. The goal is to write a function that returns the correct average for all valid inputs.

You should use python's builtin functions sum and len for this

def average(values):
    return sum(values)/len(values)

For Python 2 you have to wrap the sum(values) (or the len(values), either part of the division is good) inside a call to float.

Starting with Python 3.4 you can use the function mean from the statistics module.

import statistics
def average(values):
    return statistics.mean(values)

or shorter as your function is just another name for statistic's mean

average = statistics.mean

Upvotes: 2

Aaron
Aaron

Reputation: 2393

Try:

In [1]: def average(values):
   ...:     return float(sum(values))/len(values)
   ...:

In [2]: print average((-3,2,8,-1))
1.5

Add a float to the sum function to work for Python 2.

Upvotes: 0

Related Questions