hkus10
hkus10

Reputation: 463

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 out three element in a tuple which means if the original tuple = (1, 2, 3) which give me tuple = (2, 2, 2)

My question is there any way to condense what wrote to give me the same answer? If yes, how to condense it?

Thanks

Upvotes: 3

Views: 186

Answers (5)

eyquem
eyquem

Reputation: 27575

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

Upvotes: 0

Benjamin
Benjamin

Reputation: 11860

def average(tup):
    return (sum(tup) / len(tup),) * len(tup)

Upvotes: 0

Wesley
Wesley

Reputation: 10852

There are ways to condense the code you listed, but what you should really strive for is making 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 benefit of being able to accept tuples of any input length.

One change that was made in this version of the code is that the elements of the tuple are not first coerced to integers. Unless there is some specialised reason why you need this, you should probably separate that logic out into a separate bit of code.

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)

Of course, if you insist on a condensed answer, Sven's answer is functionally equivalent to mine.

Upvotes: 1

rubik
rubik

Reputation: 9104

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 piece of code is better than these.

Upvotes: 0

Sven Marnach
Sven Marnach

Reputation: 601679

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

Upvotes: 5

Related Questions