Python interview Question

Question

Explain the use of map and reduce in python?

in progress 0
Priyabrata 4 years 1 Answer 961 views Master 0

Answer ( 1 )

  1. Map and Reduce are paradigms of functional programming. They allow the programmer
    to write simpler, shorter code, without the need to bother about intricacies like loops.
    Both of these functions allow you to apply a function across a number of iterables, in one full swoop.

    The map function has the syntax:
    map(func, iterable)

    The map function returns a Generator object which can be converted to list.
    Example :

    players = [‘shikhar’, ‘rohit’, ‘virat’, ‘dhoni’]
    u_players = list(map(str.upper, players ))
    print(u_players)
    #output
    [‘SHIKHAR’, ‘ROHIT’, ‘VIRAT’, ‘DHONI’]

    Reduce applies a function of two arguments cumulatively to the elements of an iterable,
    optionally starting with an initial argument. It has the following syntax:

    reduce(func, iterable[, initial])

    Where func is the function on which each element in the iterable gets cumulatively applied to,
    and initial is the optional value that gets placed before the elements of the iterable in the calculation,
    and serves as a default when the iterable is empty.

    func requires two arguments, the first of which is the first element in iterable (if initial is not supplied) and the second the second element in iterable. If initial is supplied, then it becomes the first argument to func and the first element in iterable becomes the second element.

    Example:
    from functools import reduce
    numbers = [3, 4, 6, 9, 34, 12]

    def custom_sum(first, second):
    return first + second

    result = reduce(custom_sum, numbers)
    print(result)
    #output
    68

    reduce takes the first and second elements in numbers and passes them to custom_sum respectively.
    custom_sum computes their sum and returns it to reduce. reduce then takes that result and applies it
    as the first element to custom_sum and takes the next element (third) in numbers as the second element
    to custom_sum. It does this continuously (cumulatively) until numbers is exhausted.

Leave an answer

Browse
Browse