Created
March 7, 2016 04:54
-
-
Save giwa/9c2467f0ab0795437129 to your computer and use it in GitHub Desktop.
EP 15 Know How Closures Interact with Variable Scope ref: http://qiita.com/giwa/items/ef67c710fd007039c48a
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sort_priority(values, group): | |
def helper(x): | |
if x in group: | |
return (0, x) | |
return (1, x) | |
values.sort(key=helper) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
In [2]: numbers = [8, 3, 1, 2, 4, 5, 7,6] | |
In [3]: group = {2, 3, 5, 7} | |
In [4]: sort_priority(numbers, group) | |
In [5]: print(numbers) | |
[2, 3, 5, 7, 1, 4, 6, 8] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sort_priority2(numbers, group): | |
found = False # Scope: sort_priority2 | |
def helper(x): | |
if x in group: | |
found = True # Scope: helper -- Bad | |
return 0, x | |
return 1, x | |
numbers.sort(key=helper) | |
return found |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> l = [4, 6,2,5,7,9, 0] | |
>>> found = sort_priority2(l, [2,5,8]) | |
>>> found | |
False | |
>>> l | |
[2, 5, 0, 4, 6, 7, 9] | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def sort_priority2(numbers, group): | |
found = False # Scope: sort_priority2 | |
def helper(x): | |
nonlocal found | |
if x in group: | |
found = True # Scope: helper -- Bad | |
return 0, x | |
return 1, x | |
numbers.sort(key=helper) | |
return found |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment