程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

python 面试题1

发布于2019-07-13 11:59     阅读(5834)     评论(0)     点赞(18)     收藏(96)


 

python 面试题 - 知识点整理

分类: python面试
 

目录(?)[+]

 

 

1. 在判断object是否是class的instances时,type和isinstance函数的区别?

type(obj) => <type 'instance'>

type(cls) => <type 'classobj'>

由上可知,所有obj type后统一为 instance type; 而cls type后统一为classobj type

isinstance(obj,class),如果object是class的instance,返回True。

 

2. 通过重写内建函数,实现文件open之前检查文件格式?

 

  1. <span style="font-size:14px;">#! /usr/bin/env python  
  2. # -*- coding: utf-8 -*-  
  3. # vim: tabstop=shiftwidth=softtabstop=4  
  4.   
  5. def open(filename,mode):  
  6.     import __builtin__  
  7.       
  8.     file = __builtin__.open(filename,mode)  
  9.       
  10.     if file.read(5) not in("GIF87", "GIF89"):   
  11.         raise IOError, "not aGIF file"  
  12.     file.seek(0)   
  13.     return file  
  14.       
  15. fp = open("sample/test.gif","r")  
  16. print len(fp.read()), "bytes"</span>  

3. 重新实现str.strip(),注意不能使用string.*strip()

 

 

  1. <span style="font-size:14px;">#! /usr/bin/env python  
  2. # -*- coding: utf-8 -*-  
  3. # vim: tabstop=shiftwidth=softtabstop=4  
  4.   
  5.   
  6. # TODO rstrip  
  7. def rightStr(string,split=' '):  
  8.     endind = string.rfind(split)  
  9.     res = string  
  10.     while endind != -1 and endind == len(res)-1:  
  11.         res = res[:endind]  
  12.         endind = res.rfind(split)  
  13.       
  14.     return res  
  15.   
  16.   
  17. # TODO lstrip  
  18. def leftStr(string,split=' '):  
  19.     startind = string.find(split)  
  20.     res = string  
  21.     while startind != -1 and startind == 0:  
  22.         res = res[startind+1:]  
  23.         startind=res.find(split)  
  24.           
  25.     return res  
  26.   
  27. def main():  
  28.       
  29.     word='aa    asdf  aa  '  
  30.     stripstr=' '  
  31.       
  32.     lenth = len(word)  
  33.     res=word  
  34.     # leftstrip  
  35.     if word[0] == stripstr:  
  36.         res=leftStr(res)  
  37.       
  38.     # rightstrip  
  39.     if word[len(word)-1] == stripstr:  
  40.         res=rightStr(res)  
  41.       
  42.     print res  
  43.   
  44. if __name__ == "__main__":  
  45.     main()  
  46.     </span>  

4. 说明os,sys模块不同,并列举常用的模块方法?

官方解释:
os: This module provides a portable way of using operating system dependent functionality. 
翻译:提供一种方便的使用操作系统函数的方法。
sys:This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.
翻译:提供访问由解释器使用或维护的变量和在与解释器交互使用到的函数。
os 常用方法

  1. os.remove()删除文件  
  2. os.rename()重命名文件  
  3. os.walk()生成目录树下的所有文件名  
  4. os.chdir()改变目录  
  5. os.mkdir/makedirs创建目录/多层目录  
  6. os.rmdir/removedirs删除目录/多层目录  
  7. os.listdir()列出指定目录的文件  
  8. os.getcwd()取得当前工作目录  
  9. os.chmod()改变目录权限  
  10. os.path.basename()去掉目录路径,返回文件名  
  11. os.path.dirname()去掉文件名,返回目录路径  
  12. os.path.join()将分离的各部分组合成一个路径名  
  13. os.path.split()返回(dirname(),basename())元组  
  14. os.path.splitext()(返回filename,extension)元组  
  15. os.path.getatime\ctime\mtime分别返回最近访问、创建、修改时间  
  16. os.path.getsize()返回文件大小  
  17. os.path.exists()是否存在  
  18. os.path.isabs()是否为绝对路径  
  19. os.path.isdir()是否为目录  
  20. os.path.isfile()是否为文件  

sys 常用方法
  1. sys.argv           命令行参数List,第一个元素是程序本身路径    
  2. sys.modules.keys() 返回所有已经导入的模块列表    
  3. sys.exc_info()     获取当前正在处理的异常类,exc_type、exc_value、exc_traceback当前处理的异常详细信息    
  4. sys.exit(n)        退出程序,正常退出时exit(0)    
  5. sys.hexversion     获取Python解释程序的版本值,16进制格式如:0x020403F0    
  6. sys.version        获取Python解释程序的版本信息    
  7. sys.maxint         最大的Int值    
  8. sys.maxunicode     最大的Unicode值    
  9. sys.modules        返回系统导入的模块字段,key是模块名,value是模块    
  10. sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值    
  11. sys.platform       返回操作系统平台名称    
  12. sys.stdout         标准输出   
  13. sys.stdin          标准输入   
  14. sys.stderr         错误输出   
  15. sys.exc_clear()    用来清除当前线程所出现的当前的或最近的错误信息   
  16. sys.exec_prefix    返回平台独立的python文件安装的位置   
  17. sys.byteorder      本地字节规则的指示器,big-endian平台的值是'big',little-endian平台的值是'little'   
  18. sys.copyright      记录python版权相关的东西   
  19. sys.api_version    解释器的C的API版本   
  20. sys.version_info    

 

5. deepcopy 和 copy的区别?

copy 仅拷贝对象本身,而不拷贝对象中引用的其它对象。

deepcopy 除拷贝对象本身,而且拷贝对象中引用的其它对象。

例如:

 

  1. #! /usr/bin/env python  
  2. # -*- coding: utf-8 -*-  
  3. # vim: tabstop=shiftwidth=softtabstop=4  
  4.   
  5. import copy  
  6.   
  7. al = [[1],[2],[3]]  
  8. bl = copy.copy(al)  
  9. cl = copy.deepcopy(al)  
  10.   
  11. print "before=>"  
  12. print al  
  13. print bl  
  14. print cl  
  15.   
  16. al[0][0] = 0  
  17. al[1] = None  
  18.   
  19. print "after=>"  
  20. print al  
  21. print bl  
  22. print cl  

 

6. os.path和sys.path的区别?

os.path是module,包含了各种处理长文件名(路径名)的函数。

例如:

 

  1. #! /usr/bin/env python  
  2. # -*- coding: utf-8 -*-  
  3. # vim: tabstop=shiftwidth=softtabstop=4  
  4.   
  5. import os  
  6. filename = "my/little/pony"  
  7. print "using", os.name, "..."  
  8. print "split", "=>", os.path.split(filename)  
  9. print "splitext", "=>", os.path.splitext(filename)  
  10. print "dirname", "=>", os.path.dirname(filename)  
  11. print "basename", "=>", os.path.basename(filename)  

sys.path是由目录名构成的列表,Python 从中查找扩展模块( Python 源模块, 编译模块,或者二进制扩展). 启动 Python 时,这个列表从根据内建规则,PYTHONPATH 环境变量的内容, 以及注册表( Windows 系统)等进行初始化. 

 

 

7. re模块中match和search方法的不同?

match() 函数只检查 RE 是否在字符串开始处匹配,而 search() 则是扫描整个字符串。

 

8. 如何匹配<html><title></title></html>得到<html>

 

  1. >>> import re  
  2. >>str = r'<html><title></title></html>'  
  3. >>p = re.compile(r'<.*?>')  
  4. >>> print p.match(str).group(0)  

 

9. 重新实现filter,map,reduce。

 

  1. #! /usr/bin/env python  
  2. # -*- coding: utf-8 -*-  
  3. # vim: tabstop=shiftwidth=softtabstop=4  
  4.   
  5. def filter_impl(func, argvs):  
  6.     res = []  
  7.       
  8.     for argv in argvs:  
  9.         if func(argv):  
  10.             res.append(argv)  
  11.       
  12.     return res  
  13.   
  14.   
  15. # check filter impl  
  16. print "filter ==>"  
  17. print filter_impl(lambda x: x<4, range(1,10))  
  18. print filter(lambda x: x<4, range(1,10))  
  19.   
  20. def map_impl(func, argvs):  
  21.   
  22.     res = []  
  23.     for argv in argvs:  
  24.         res.append(func(argv))  
  25.           
  26.     return res  
  27.   
  28. # check map impl  
  29.   
  30. print "map ==>"  
  31. print map_impl(lambda x: x*10, range(1,5))  
  32. print map(lambda x: x*10, range(1,5))  
  33.   
  34. def reduce_impl(func, argvs, startVal=None):  
  35.       
  36.     if startVal is not None:  
  37.         argv1 = startVal  
  38.     else:  
  39.         argv1 = argvs[0]  
  40.       
  41.     for argv2 in argvs[1:]:  
  42.         argv1 = func(argv1, argv2)  
  43.       
  44.     return argv1  
  45.           
  46. # check reduce impl  
  47. print "reduce ==>"  
  48. print reduce_impl(lambda x,y: x*y, range(1,4),20)  
  49. print reduce(lambda x,y: x*y, range(1,4),20)  

 

Result:

filter ==>
[1, 2, 3]
[1, 2, 3]
map ==>
[10, 20, 30, 40]
[10, 20, 30, 40]
reduce ==>
120
120

 

10. 解释生成器(generator)与函数的不同,并实现和使用简单generator?

生成器和函数的主要区别在于函数 return a value,生成器 yield a value同时标记或记忆 point of the yield 以便于在下次调用时从标记点恢复执行。 yield 使函数转换成生成器,而生成器反过来又返回迭代器。

 

  1. #! /usr/bin/env python  
  2. # -*- coding: utf-8 -*-  
  3. # vim: tabstop=shiftwidth=softtabstop=4  
  4.   
  5. def gem():  
  6.     yield "first"  
  7.     yield "second"  
  8.     yield "third"  
  9.       
  10. for res in gem():  
  11.     print res  

11. 设计实现遍历目录与子目录,抓取.pyc文件?

 

  1. #! /usr/bin/env python  
  2. # -*- coding: utf-8 -*-  
  3. # vim: tabstop=shiftwidth=softtabstop=4  
  4.   
  5. # 1. for-in dir/subdir to get the filesname  
  6. # 2. splitext filename to filter  
  7.   
  8. import os  
  9.   
  10. def getFiles(dir, suffix):  
  11.       
  12.     res = []  
  13.     for root,directory,files in os.walk(dir):  
  14.         for filename in files:  
  15.             name, suf = os.path.splitext(filename)  
  16.             if suf == suffix:  
  17.                 res.append(os.path.join(root, filename))  
  18.     return res  
  19.   
  20. for file in getFiles("./", '.py'):  
  21.     print file  


所属网站分类: 技术文章 > 博客

作者:lg

链接:https://www.pythonheidong.com/blog/article/1225/9a8880e7292c9bfec961/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

18 0
收藏该文
已收藏

评论内容:(最多支持255个字符)