A function is called Higher-Order Function if it contains other functions as a parameter or returns a function as an output. We can pass functions as arguments, we can return functions as well. All of this makes it very convenient to write generic code which can be reused in multiple places.
sorted()for instance, is a higher-order function. We can pass an argument called
keyto it, which will be used to determine how the sorting is done. We can have a list of tuples and would like to sort the list based on the sum of the elements of tuples:
items = [(3, 6), (1, 8), (4, 4), (6, 1)] items.sort(key=lambda x: x + x) print(items) # [(6, 1), (4, 4), (3, 6), (1, 8)]
Here, we’ve passed a lambda function that takes a single element as an argument and returns the value according to which it should be sorted.
We can define our own higher-order function as well:
def do(num1, num2, operation): res = operation(num1, num2) print(num1, num2, res) do(2, 3, lambda x, y: x + y) # 2 3 5 do(2, 3, lambda x, y: x - y) # 2 3 -1 do(2, 3, lambda x, y: x * y) # 2 3 6
do()has 3 arguments - the first number
num1, the second number
num2, and the operation that needs to be performed on those numbers. In the first call, we tell the function to use addition, in the second one to use subtraction, and in the final one multiplication.
Given a list of
ntriplets of numbers, you are asked to sort those triplets by their sum. So, in the final list, if we look at the sum of the triplets, the result is a non-decreasing sequence.
The first line of the input contains a single integer
n- the number of triplets. The next
nlines contain 3 space-separated integers.
The program should print
nlines - the resulting list of triplets. Each line should contain 3 space-separated numbers. If there are two triplets with the same sum, the first one appearing in the input should appear first in the output (
sortedfunctions keep that order - this is called stable sorting).
3 10 4 0 12 1 1 6 7 8
10 4 0 12 1 1 6 7 8
Time limit: 1 seconds
Memory limit: 512 MB
Output limit: 1 MB