1

I am trying to convert a labda function in normal function but unable to understand it.

def closest(u): 
    return min(updated_unique_list, key=lambda v: len(set(u) ^ set(v)))

how this labda and min works?
I tried to understand from docs but I want to understand with this example and to create a normal function instead of this lambda function.

1
  • 1
    from python help min(...) min(iterable[, key=func]) -> value min(a, b, c, ...[, key=func]) -> value With a single iterable argument, return its smallest item. With two or more arguments, return the smallest argument. Commented Dec 15, 2011 at 5:57

1 Answer 1

4

min find the minimum value of an iterable with respect to a function. min(lst, key=func) in Python can be roughly considered as (ignoring details like calling f as little as possible or walking through the list only once)

retval = lst[0]
for item in lst:
  if func(item) < func(retval):
     retval = item
return retval

In your case, it finds the item v in updated_unique_list such that len(set(u) ^ set(v)) is minimum.

Now, ^ between two set is their symmetric difference. set(u) ^ set(v) returns a set of elements that does not appear in both u and v. The size of the result will be zero if u and v are equal, and is maximum if they do not overlap at all.

Therefore, the function tries to find an object in the updated_unique_list which has the most common elements with u.

If you want the "normal function" just expand the min according to the algorithm I've described above.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks.what us this f(items)? can u explain me in terms of updated_unique_list= ["page", "text", "footer", "header", "title", "good morning"] and u="those"
@sam: Sorry I meant func(item) (corrected). Apply the key function to each item. In your case func("page") would become len(set("page") ^ set("those")).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.