referce:python interview questions top 50

refercence:python interview questions top 15

summary

A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
A1 = range(10)
A2 = sorted([i for i in A1 if i in A0])
A3 = sorted([A0[s] for s in A0])
A4 = [i for i in A1 if i in A3]
A5 = {i:i*i for i in A1}
A6 = [[i,i*i] for i in A1]

A:

A0 = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}  # the order may vary
A1 = range(0, 10) # or [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] in python 2
A2 = []
A3 = [1, 2, 3, 4, 5]
A4 = [1, 2, 3, 4, 5]
A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]
def f(*args,**kwargs): print(args, kwargs)
l = [1,2,3]
t = (4,5,6)
d = {'a':7,'b':8,'c':9}
f(l)
f(d)
f(l,d)
f(*l,**d)

output:

([1, 2, 3],) {}
({'a': 7, 'b': 8, 'c': 9},) {}
([1, 2, 3], {'a': 7, 'b': 8, 'c': 9}) {}
(1, 2, 3) {'a': 7, 'b': 8, 'c': 9}
@my_decorator
def my_func(stuff):
do_things
equivalent to
def my_func(stuff):
do_things
my_func = my_decorator(my_func)

count run efficiency

import cProfile
cProfile.run("func('para')")
# code at m.py
class MyClass:
def f(self):
print "f()"
import m
def monkey_f(self):
print "monkey_f()" m.MyClass.f = monkey_f
obj = m.MyClass()
obj.f()

output:

monkey_f()

conclusion: the term monkey patch only refers to dynamic modifications of a class or module at run-time.

05-11 15:38
查看更多