Tuple function that returns certain parameters

Question:

I’m stuck on an exercise where I should do a function which makes a tuple out of 3 given numbers and returns tuple following these rules:

  • 1st element must be the smallest parameter
  • 2nd element must be the biggest parameter
  • 3rd element is the sum of parameters

For example:

> print(do_tuple(5, 3, -1))
# (-1, 5, 7)

What I have so far:

def do_tuple(x: int, y: int, z: int):
    
    tuple_ = (x,y,z)
    summ = x + y + z
    mini = min(tuple_)
    maxi = max(tuple_)  
    
if __name__ == "__main__":
    print(do_tuple(5, 3, -1))

I know I should be able to sort and return these values according to the criteria but I can’t work my head around it..

Asked By: Fontana dot py

||

Answers:

You need to return the tuple inside your function

def do_tuple(x: int, y: int, z: int):
    
    tuple_ = (x,y,z)
    summ = x + y + z
    mini = min(tuple_)
    maxi = max(tuple_)
    return (mini, maxi, summ)
   
    
if __name__ == "__main__":
    print(do_tuple(5, 3, -1))
Answered By: Guillaume BEDOYA

As already indicated in a previous answer, you just have to add a return statement in your function. Additionnally, you can use packing to simplify and manage a variable number of arguments. Finally it results in a one-lined and easy-to-read function, as follows:

def do_tuple(*args):
    return (max(args), min(args), sum(args))
   
print(do_tuple(5, 3, -1))  # (5, -1, 7)
Answered By: Laurent H.
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.