HiThere HiThere - 7 months ago 13
Python Question

How to rewrite anonymous functions?

I'm new to programming and Python particularly Python3. Using an online tutorial I'm trying to understand the use of 'lambda'. Therefore, I would like to rewrite the following code and use other named functions, list comprehension, dict comprehension or generator. However struggle with the syntax. I'm not able to rewrite the

lambdas
.

Original function:

import functools as ft
import itertools as it
import os
import re
import requests
import tempfile
def foo(los, n=None):
n = n or len(los)
h = it.takewhile(lambda p: p[0] < n, enumerate(los))
s = sorted(h, key=lambda p: p[1])
g = it.groupby(s, lambda p: p[1])
return dict(it.starmap(lambda k, vs: (k, sum(map(lambda i: 1, vs))), g))

alist=[1,2,3,1,1,7,8,9,9]

print(foo(alist))

{1: 3, 2: 1, 3: 1, 7: 1, 8: 1, 9: 2}


My adjustment:

def smaller_then_ten(e):
return e[0] < len(e)

def foo(los, n=None):
n = n or len(los)
h = it.takewhile(smaller_then_n, enumerate(los))
s = sorted(h)
g = it.groupby(s)
return dict(it.starmap(lambda k, vs: (k, sum(map(lambda i: 1, vs))), g))

alist=[1,2,3,1,1,7,8,9,9]

print(foo(alist))

Answer

You can rewrite it like this...

For:

lambda args: expression_with_args

a function would look like:

def func_name(args):
    return expression_with_args

E.g.

lambda p: p[0] < n

becomes:

def compare_func(p, n):
    return p[0] < n

to use it as a function for key, which takes only one argument it has to be modified a little to save the value of n:

compare_func = ft.partial(compare_func, n=n)

E.g.

lambda p: p[1]

becomes:

def get_first(p):
    return p[1]

E.g.

lambda k, vs: (k, sum(map(lambda i: 1, vs)))

becomes:

def as_one(i):
    return 1

def get_tuple(k, vs):
    vs_with_ones = map(as_one, vs)
    vs_sum = sum(vs_with_ones)
    return (k, vs_sum)

Finally:

def foo(los, n=None):
    n = n or len(los)
    compare_func = ft.partial(compare_func, n=n)
    h = it.takewhile(compare_func, enumerate(los))
    s = sorted(h, key=get_first)
    g = it.groupby(s, get_first)
    return dict(it.starmap(get_tuple, g))
Comments