pythonpython-3.xlambdastarmap

How to write a starmap-like function without using the builtin map or starmap?


This is the task:

Make a function my_map_k that as arguments takes a function f and k lists L1,...,Lk, for an arbitrary k ≥ 1, and returns the list [f(L1[0],...,Lk[0]),...,f(L1[n-1],...,Lk[n-1])], where n is the length of the shortest Li list.

Hint. Use Python's * notation to handle an arbitrary number of lists as arguments.

Example:

my_map_k(lambda x, y, z: x*y*z, [3, 2, 5], [2, 7, 9], [1, 2])

should return [6, 28].

This is how far I've gotten, but I'm stuck.

def my_map_k(f, *L):
    n = len(min(*L, key=len))
    x=0
    while x < n:
        return [f(*L[x],) for x in L]

my_map_k(lambda x, y, z: x*y*z, [3, 2, 5], [2, 7, 9], [1, 2])

The problem is, I cannot just say that there are 3 lists, because there could be more. Furthermore I cannot see how to take the first element out of all three lists.


Solution

  • You can use zip() to take the nth element from each list in turn, and a list comprehension to call the supplied function with each group of arguments so generated:

    def my_map_k(f, *lists):
        return [f(*args) for args in zip(*lists)]
    

    Here it is in action:

    >>> my_map_k(lambda x, y, z: x*y*z, [3, 2, 5], [2, 7, 9], [1, 2])
    [6, 28]