lintcode-solutions
  • LintCode 刷题笔记
  • 课程笔记
    • Backtracking
    • Binary Search
    • Divide & Conquer
    • Breadth First Search
    • Depth First Search
    • Linked List & Array
    • Two Pointers
    • Stack, Queue and Heap
    • Dynamic Programming
    • Two Pointers Advanced
    • Union Find and Trie
    • Dynamic Programming Advanced
  • 基础知识储备
    • Python
      • Stack and Queue
      • Namedtuple
      • Priority Queue
      • isinstance()
      • OrderedDict
      • set and frozen set
      • Counter
      • Heap
    • Bit Manipulation
    • Fenwick Tree or Binary Indexed Tree
    • Rabin-Karp Algorithm
    • Sort
      • Merge Sort
      • Quick Sort
      • Heap Sort
  • LintCode 练习题
    • Binary Search
  • OJ Review
    • Aug 7, 2018
    • Aug 8, 2018
    • Aug 9, 2018
    • Aug 13, 2018
    • Aug 17, 2018
    • Aug 19, 2018
    • Aug 24, 2018
    • Aug 26, 2018
    • Aug 27, 2018
    • Aug 29, 2018
    • Sep 1, 2018
    • Sep 2, 2018
    • Sep 3, 2018
    • Sep 4, 2018
    • Oct 28, 2018
    • Nov 13, 2018
Powered by GitBook
On this page
  • Python
  • Iterating through two lists in parallel using zip()
  • Closures
  • References
  1. OJ Review

Sep 3, 2018

PreviousSep 2, 2018NextSep 4, 2018

Last updated 6 years ago

Python

def check_equal(str1, str2):
    if len(str1) != len(str2):
        return False;
    i = 0
    j = 0
    for i, j in zip(str1, str2):
        if i != j:
            return False;
    return True

前天学习Rabin-Karp之后没有自己看Tushar写的代码,今天一下,嗯?骚操作?注意到上一段代码有这样一个操作 for i, j in zip(str1, str2):

Iterating through two lists in parallel using zip()

From the , zip returns a list of tuples, where the i_th tuple contains the i_th element from each of the argument sequences or iterables. This is useful for iterating over two lists in parallel. For example, if I have two lists, I can get the first element of both lists, then the second element of both lists, then the third, etc.

Python 2.5.1 (r251:54863, May 18 2007, 16:56:43)
[GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = [1,2,3]
>>> b = ['a','b','c']
>>> for i,j in zip(a,b):
...     print i, j
...
1 a
2 b
3 c
>>> 

If the lists are different lengths, zip truncates to the length of the shortest list. Using map with None is similar to zip except the results are padded with None.

>>> a = [1,2,3]
>>> b = ['a','b','c','d']
>>> zip(a,b)
[(1, 'a'), (2, 'b'), (3, 'c')]
>>> map(None,a,b)
[(1, 'a'), (2, 'b'), (3, 'c'), (None, 'd')]
>>> 

If I have a list of keys and a list of values, I can create a dictionary by passing the output of zip to dict.

>>> mykeys = ['a', 'b', 'c']
>>> myvalues = [1, 2, 3]
>>> dict(zip(mykeys, myvalues))
{'a': 1, 'c': 3, 'b': 2}
>>> 

Closures

A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory. Let us get to it step by step

Firstly, a Nested Function is a function defined inside another function. It's very important to note that the nested functions can access the variables of the enclosing scope. However, at least in python, they are only read only. However, one can use the "nonlocal" keyword explicitly with these variables in order to modify them.

For example:

def transmit_to_space(message):
    "This is the enclosing function"
    def data_transmitter():
        "The nested function"
        print(message)

    data_transmitter()

print(transmit_to_space("Test message"))
Output

Test message
None

This works well as the 'data_transmitter' function can access the 'message'. To demonstrate the use of the "nonlocal" keyword, consider this

def print_msg(number):
    def printer():
        "Here we are using the nonlocal keyword"
        nonlocal number
        number = 3
        print(number)
    printer()
    print(number)

print_msg(9)
Output:

3
3

Without the nonlocal keyword, the output would be "3 9", however, with its usage, we get "3 3", that is the value of the "number" variable gets modified.

Now, how about we return the function object rather than calling the nested function within. (Remember that even functions are objects. (It's Python.))

def transmit_to_space(message):
    "This is the enclosing function"
    def data_transmitter():
        "The nested function"
        print(message)
    return data_transmitter

And we call the function as follows:

def transmit_to_space(message):
    "This is the enclosing function"
    def data_transmitter():
        "The nested function"
        print(message)
    return data_transmitter

fun2 = transmit_to_space("Burn the Sun!")
fun2()
Output:

Burn the Sun!

Even though the execution of the "transmit_to_space()" was completed, the message was rather preserved. This technique by which the data is attached to some code even after end of those other original functions is called as closures in python

ADVANTAGE : Closures can avoid use of global variables and provides some form of data hiding.(Eg. When there are few methods in a class, use closures instead).

Also, Decorators in Python make extensive use of closures.

References

Python docs
Iterating through two lists in parallel using zip() - SaltyCrane Blog
Logo
Closures - Learn Python - Free Interactive Python Tutorial
Logo