Understanding closure in Python

This is an example from Bratt Slatkin’s book.

def sort_priority(values,   group):
    def helper(x):
        if  x   in  group:
            return  (0, x)
        return  (1, x)
    values.sort(key=helper)

In addition, they gave these values

numbers =   [8, 3,  1,  2,  5,  4,  7,  6]
group   =   {2, 3,  5,  7}
sort_priority(numbers,  group)
print(numbers)

And we have

[2, 3,  5,  7,  1,  4,  6,  8]

I do not understand this example. Why do we return twice and what does the helper function actually do?

+4
source share
4 answers

You read the function as:

def helper(x):
    if  x   in  group:
        return  (0, x)
    else:
        return  (1, x)

The intuition is that it sortaccepts a callback keythat is called for each element. For each element helper, a tuple is called that returns (it can be either (0, x), or (1, x)depending on whether it exists xin the VIP list).

, , , . , , (0, x), (1, x), 0 < 1.

: , 0, , 1. 0 , - x. 1.


:

Group0: [2, 3, 5, 7]
Group1: [8, 1, 4, 6]

Ordering within Group0: [2, 3, 5, 7]
Ordering within Group1: [1, 4, 6, 8]

Overall ordering: [Group0, Group1]

Result:  [2, 3, 5, 7,    1, 4, 6, 8]
+3

?

.

def helper(x):
    if  x  in  group:
        return  (0, x)
    return  (1, x)

def helper(x):
    if  x   in  group:
        return  (0, x)
    else:        
        return  (1, x)

, if. True, (0, x). False, (1, x).

+2

, return if. python , return, , if else. , (0,x), if , (1,x).

+1

, :

def helper(x):
    global group
    if x in group:
        return 0, x
    return 1, x


def sort_priority(values):
    values.sort(key=helper)


numbers = [8, 3, 1, 2, 5, 4, 7, 6]
group = {2, 3, 5, 7}
sort_priority(numbers)
print(numbers)

, sort_priority() , helper, , x.

helper , group - "" (), group, ().

helper :

def helper(x):
    global group
    if x in group:
        return 0, x  # <-- we're in the `if` so `x` gets zero 
    return 1, x      # <-- if we got here it means we didn't get into the `if` so `x` gets one

, helper key , , , group, , group

[2, 3, 5, 7, 1, 4, 6, 8]
             ^
            The first item that is not in group
+1

Source: https://habr.com/ru/post/1684551/


All Articles