How to condense this function?

def average(tup):
  """ ugiufh """
   total = ((int(tup[0]) + int(tup[1]) + int(tup[2]))/3,
            (int(tup[0]) + int(tup[1]) + int(tup[2]))/3,
            (int(tup[0]) + int(tup[1]) + int(tup[2]))/3)
   return total

I am writing a function to average the three elements in a tuple, which means that the original set = (1, 2, 3), which gives me a tuple = (2, 2, 2)

My question is, is there a way to condense what I wrote to give me the same answer? If so, how to condense it?

thank

+3
source share
5 answers

If you are sure you want integer division, you can use

def average(tup):
    n = len(tup)
    return (sum(int(x) for x in tup) / n,) * n
+5
source

There are ways to put together the code you pointed out, but what you really should aim for makes the code more readable.

def average(a):
    """Return a tuple where every element of ``a`` is replaced by the average of the values of ``a``."""
    length = len(a)
    average = sum(a) / length
    return (average,) * length # A 1-tuple containing the average, repeated length times

This has the added advantage of being able to accept tuples of any input length.

, , , . - , , , , .

data = (1, '2', 3.0)
normalised_data = (int(x) for x in data) # A generator expression that yields integer-coerced elements of data
result = average(normalised_data)

, , Sven .

+1
def average(tup):
    def mean(t):
        return sum(t, .0) / len(t)
    return (mean(tup),) * len(tup)

One line:

def average(tup): return ((lambda t: sum(t, .0) / len(t))(tup),) * len(tup)

or

average = lambda tup: ((lambda t: sum(t, .0) / len(t))(tup),) * len(tup)

But the first part of the code is better than these.

0
source
def average(tup):
    return (sum(tup) / len(tup),) * len(tup)
0
source
def average(tup):
    """ ugiufh """
    el = sum( map(int,tup) )/3
    return (el,el,el)
0
source

All Articles