python 面试( interview )

总结面试中关于python 的问题,包括 python 数据结构,python 第三方库, python 算法,python 性能:


1. 闭包(closure):

we have a closure in Python when a nested function references a value in its enclosing scope.

The criteria that must be met to create closure in Python are summarized in the following points.

  • We must have a nested function (function inside a function).
  • The nested function must refer to a value defined in the enclosing function.
  • The enclosing function must return the nested function.
def fuc():

	return [lambda x: i * x for i in range(4)]

print(fuc())

print([m(2) for m in fuc()])

Output:

[6, 6, 6, 6]

reference for why is good to use closure


2. nonlocal 变量:

nonlocal is used to declare that a variable inside a nested function (function inside a function) is not local to it, meaning it lies in the outer enclosing function. If we need to modify the value of a non-local variable inside a nested function, then we must declare it with nonlocal. Otherwise a local variable with that name is created inside the nested function.

def outer_funciton():
    a = 5
    def inner_function():
        nonlocal a
        a = 10
        print("Inner function: ",a)
    inner_function()
    print("Outer function: ",a)

outer_funciton()

Output:

Inner function:  10
Outer function:  10

3.默认参数:

The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

def fuc(var, ls = []):

	ls.append(var)

	print(ls)


fuc(123)

fuc('a', [])

fuc('b')
Output:

[123]
['a']
[123, 'b']

4.quickSort(快排):

from random import randrange

def partition(lst, start, end, pivot):
    lst[pivot], lst[end] = lst[end], lst[pivot]

    store_index = start

    for i in xrange(start, end):

        if lst[i] < lst[end]:

            lst[i], lst[store_index] = lst[store_index], lst[i]

            store_index += 1

    lst[store_index], lst[end] = lst[end], lst[store_index]

    return store_index


def quick_sort(lst, start, end):
    if start >= end:

        return lst

    pivot = randrange(start, end + 1)

    new_pivot = partition(lst, start, end, pivot)

    quick_sort(lst, start, new_pivot - 1)

    quick_sort(lst, new_pivot + 1, end)

def sort(lst):
    quick_sort(lst, 0, len(lst) - 1)

    return lst


print sort([])

print sort([1, 2, 3, 4])








你可能感兴趣的:(Python)