python 面试题1

分类: python面试2013-03-05 15:52 13754人阅读 评论(1) 收藏举报

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之前检查文件格式?

[html]view plaincopyprint?

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

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

[html]view plaincopyprint?

  1. <span >#! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # vim: tabstop=4 shiftwidth=4 softtabstop=4
  4. # TODO rstrip
  5. def rightStr(string,split=' '):
  6. endind = string.rfind(split)
  7. res = string
  8. while endind != -1 and endind == len(res)-1:
  9. res = res[:endind]
  10. endind = res.rfind(split)
  11. return res
  12. # TODO lstrip
  13. def leftStr(string,split=' '):
  14. startind = string.find(split)
  15. res = string
  16. while startind != -1 and startind == 0:
  17. res = res[startind+1:]
  18. startind=res.find(split)
  19. return res
  20. def main():
  21. word='aa asdf aa '
  22. stripstr=' '
  23. lenth = len(word)
  24. res=word
  25. # leftstrip
  26. if word[0] == stripstr:
  27. res=leftStr(res)
  28. # rightstrip
  29. if word[len(word)-1] == stripstr:
  30. res=rightStr(res)
  31. print res
  32. if __name__ == "__main__":
  33. main()
  34. </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 常用方法

[html]view plaincopyprint?

  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 常用方法

[html]view plaincopyprint?

  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 除拷贝对象本身,而且拷贝对象中引用的其它对象。

例如:

[html]view plaincopyprint?

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

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

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

例如:

[html]view plaincopyprint?

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

[html]view plaincopyprint?

  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。

[html]view plaincopyprint?

  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # vim: tabstop=4 shiftwidth=4 softtabstop=4
  4. def filter_impl(func, argvs):
  5. res = []
  6. for argv in argvs:
  7. if func(argv):
  8. res.append(argv)
  9. return res
  10. # check filter impl
  11. print "filter ==>"
  12. print filter_impl(lambda x: x<4, range(1,10))
  13. print filter(lambda x: x<4, range(1,10))
  14. def map_impl(func, argvs):
  15. res = []
  16. for argv in argvs:
  17. res.append(func(argv))
  18. return res
  19. # check map impl
  20. print "map ==>"
  21. print map_impl(lambda x: x*10, range(1,5))
  22. print map(lambda x: x*10, range(1,5))
  23. def reduce_impl(func, argvs, startVal=None):
  24. if startVal is not None:
  25. argv1 = startVal
  26. else:
  27. argv1 = argvs[0]
  28. for argv2 in argvs[1:]:
  29. argv1 = func(argv1, argv2)
  30. return argv1
  31. # check reduce impl
  32. print "reduce ==>"
  33. print reduce_impl(lambda x,y: x*y, range(1,4),20)
  34. 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 使函数转换成生成器,而生成器反过来又返回迭代器。

[html]view plaincopyprint?

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

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

[html]view plaincopyprint?

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