python笔试编程题_python_编程面试题
使用递归方法对一个数组求最大值和最小值
"""用递归算法求解一个数组的最大值和最小值
思路:
1、首先假设这个列表只有1个元素或两个元素
2、再考虑超过两个元素的情况,将该列表从中间位置一分为二
3、然后递归调用该函数"""
defmyMaxMin(L,start,end):'''递归来得到数组的最大值和最小值'''
if end - start <= 1:#基准点的情况
return(max(L[start],L[end]),min(L[start],L[end]))else:
max1, min1= myMaxMin(L,start,(start+end)//2)#求前半部分的
max2, min2 = myMaxMin(L,(start+end)//2+1,end)#求后半部分的
returnmax(max1,max2),min(min1,min2)defmaxMin(L):assert(type(L) == type([]) and len(L) >0)
maxV, minV= myMaxMin(L,0,len(L)-1)print(maxV,minV)returnmaxV, minV
L= [1,3,5,6,7,8,5,7,8,-9]assert(maxMin(L) == (8,-9))
使用递归的方法求出10个球的颜色可能性打印出来(颜色只有黑、白两种)
'''有10个球,每个球有两种颜色选择,黑与白,使用递归的方法把这10个球的颜色可能性打印出来
1、将这10个球放入到一个列表中,全部用0表示,0表示白,1表示黑
2、找基准点(程序结束的条件)start = end,打印结果'''count=0defperm(L,start,end):if start == end:#基准点,表示已经给每个球都赋值了一个颜色
print(L)globalcount
count+= 1
else:
perm(L,start+1,end)
L[start]= (L[start]+1)%2#实现1与0的互换
perm(L,start+1,end)
L=[0,0,0,0,0,0,0,0,0,0]
res=perm(L,0,len(L))print(count)#1024,2**10
使用两个栈实现一个队列
'''使用两个栈实现一个队列
队列:a,b,c -->c,b,a'''
classQueueWithStacks:def __init__(self):
self.s1=[]
self.s2=[]defpush(self,e):
self.s1.append(e)defpop(self):if len(self.s2) ==0:while len(self.s1) >0:
t=self.s1.pop()
self.s2.append(t)assert len(self.s2) > 0,'队列已经为空'#此时说明队列没有元素
returnself.s2.pop()
q=QueueWithStacks()
q.push('a')
q.push('b')
q.push('c')print(q.pop())print(q.pop())print(q.pop())print(q.pop())#AssertionError: 队列已经为空
实现单例模式
classSingleton:__instance =None
@classmethoddefget_instance(cls):if cls.__instance:return cls.__instance
else:
cls.__instance =Singleton()return cls.__instanceobj1=Singleton.get_instance()print(obj1) #<__main__.Singleton object at 0x7eff2ce22b70>
obj2 =Singleton.get_instance()print(obj2) #<__main__.Singleton object at 0x7eff2ce22b70>
classSingleton(object):def __new__(cls, *args, **kwargs):if not hasattr(cls,'_instance'):
cls._instance= super(Singleton,cls).__new__(cls)returncls._instance
s1=Singleton()
s2=Singleton()print(s1 == s2) # True
闭包
deffoo():return [lambda x: i+x for i in range(4)]print([x(3) for x infoo()])#将上面的程序改写,以便更好的理解
deffoo():
function_list=[]for i in range(4):
function_list+= [lambda x: i+x]return function_list #返回一个存有四个函数的列表
#x其实就是表示x=lambda x: i+x,所以x(3)就表示lambda 3: i+3,只不过此处用到了闭包的概念:i是foo函数的局部变量,x是foo的内嵌函数#内嵌函数引用外部函数的变量i,当foo函数执行完毕返回一个函数列表时,i的值已经是3了,所以当x函数中的i就是3,所以结果就是[3+3,3+3,3+3,3+3]
print([x(3) for x in foo()])
编译一个目录,找出该目录下的所有文件
importos
file_list=[]deftraversal_directory(dir):for child inos.listdir(dir):
parent_child=os.path.join(dir, child)ifos.path.isdir(parent_child):
traversal_directory(parent_child)else:
file_list.append(parent_child)returnfile_listif __name__ == "__main__":for file in traversal_directory("slideshow"):print(file)
is与==的区别
"""==符号判断的是字面值
is判断的是对象的地址
==符号为True则用is判断也必定为True
is判断为True时用==符号判断未必是True"""
classA:
@staticmethoddef __eq__(var):returnTrueif __name__ == "__main__":print(A() == 1) # Trueprint(A() is 1) # Falseprint("A()的id",id(A()))print("1的id",id(1))
python与C语言在运行效率上哪个更快,并编写代码验证
求第45个斐波那契数
importtimedeffun(n):if n <= 2:return 1
return fun(n-1) + fun(n-2)
start=time.time()
res= fun(45)
end=time.time()
tm= end -startprint(tm) # 287.7714354991913,大约5分钟print(res)
#include #include#include //导入sleep函数
long fib(intn){if(n <= 2){return 1;
}else{return fib(n-1) + fib(n-2);
}
}intmain(){
unsignedlong start = time(0);long res = fib(45);
unsignedlong end = time(0);double time = end -start;
printf("time:%f\n",time); //大约5秒钟
printf("res:%ld\n", res);return 0;
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
