# Sep 3, 2018

## Python

```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):`&#x20;

### Iterating through two lists in parallel using `zip()`

> From the [Python docs](http://docs.python.org/lib/built-in-funcs.html), `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
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`.

```python
>>> 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`.

```python
>>> 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:

```python
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

```python
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.))

```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:

```python
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

{% embed url="<https://www.saltycrane.com/blog/2007/12/iterating-through-two-lists-in-parallel/>" %}

{% embed url="<https://www.learnpython.org/en/Closures>" %}
