①写一个装饰器,可以修改函数,打印输出函数执行时长
首先要加载time模块,在timer装饰器中定义inner,因为要支持有参数的函数所以形参是*args和**kwargs这样的可变参数,用start和end记下函数开始和结束的时间,最后打印出函数消耗的时间。除此之外别忘了函数有返回值,在这里我们要先把返回值给到inner,再由装饰器传回函数调用处。
import time
def timer(func):
def inner(*args,**kwargs):
start = time.time()
result = func(*args,**kwargs)
end=time.time()
print('The used time=',end-start)
return result
return inner
@timer #这句话等同于func2 = timer(func2),意为这个函数使用timer装饰器
def func1(a,b):
print('in func2')
print(a,' is ',b)
return 'func1 is over!'
print(func1('python','nb'))
②dicta = {"a":1,"b":2,"c":3,"d":4,"f":"hello"}
dictb = {"b":3,"d":5,"e":7,"m":9,"k":"world"}
要求写一段代码,实现两个字典的相加,不同的key对应的值保留,相同的key对应的值相加后保留(假设相同key的value值的类型相同且可以做“+”操作,如果是字符串就拼接,如上示例得到结果为:
dictc = {"a":1,"b":5,"c":3,"d":9,"e":7,"m":9,"f":"hello","k":"world"}
from copy import deepcopy
dictc=deepcopy(dicta)
for key,value in dictb.items():
if key in dictc.keys():
dictc[key]+=value
else:
dictc[key]=value
③编写一个函数,输入一个列表,删除列表中的重复元素。
#法一
source_list=[1,2,3,4,5,6,2,3,4,2,2,1,6,5,5]
new_list = {}.fromkeys(source_list)
#法二
new_list = []
[new_list.append(i) for i in source_list if not i in new_list]
④编写一个斐波那契数列(从0开始)的生成器,并且在需要时可以支持从外部传入一个参数num,num表示下次要获取第num个斐波那契数。如果第num个数在之前已经取过,则下次获取时取正常的下一个斐波那契数。
def f():
x,y,i=1,1,1
while True:
try:
while i<t:
x,y=y,x+y
i+=1
except Exception:
t = yield x
x,y=y,x+y
i+=1
else:
yield x
t=None
⑤设有一段C++的代码,如下:
switch(name)
{
case 'Ram':
cout<<"Monday";
break;
case 'Shiv':
cout<<"Tuesday";
break;
default:
cout<<"Hi, user";
}
请你用python编写一个函数switch(choice)实现这段代码的功能。(不能用if elif else)
name=input("请输入name:")
end=0
while name=='Ram' :
print("Monday")
end=1
break
while name=='Shiv' :
print("Tuesday")
end=1
break
while end==0:
print("Hi, user")
break