Functions with return value
Printing in the output is great, but most of the useful functions that we have used before like
math.sqrt()do not print a value. They return a result.
max()returns the maximum among all the values passed to it.
math.sqrt()returns the square root of a number which we can use afterward in our program.
To return a value from a function, we can use the
def celsius2fahrenheit(degrees): return 9 / 5 * degrees + 32 print(celsius2fahrenheit(10)) # 50.0 print(celsius2fahrenheit(10) + celsius2fahrenheit(20)) # 118.0
We can have functions with more operations in their body before returning:
def product(numbers): res = 1 for n in numbers: res *= n return res print(product([4, 5, 6])) # 120 print(product([-1, 0, 5])) # 0
You are asked to write a function called
vote, which would return the element which appears the most frequent among the 3 numbers passed to it. If all of them are different, the function should return the first one.
The input contains 3 numbers.
The program should print a single number - the most frequent one returned by the function vote.
0 1 0
1 2 3
Time limit: 1 seconds
Memory limit: 512 MB
Output limit: 1 MB