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])








  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值