Python面试题(十三)
1、用最简洁的方式初始化这样一个变量:foo = [4,16,36,64,100]
[i*i for i in range(2,12,2)]
2、使用生成器编写fib函数,函数声明为fib(max)输入一个参数max的值,使得该函数可以这样调用
并产生如下结果(斐波那契数列),1,1,2,3,5,8,13,21
def fib(max): a = 0 b = 1 while b<max: yield b b,a = a+b,b for i in fib(1000): print(i,end=' ')
3、有如下数组list = range(10) 我想取以下几个数组,应该如何切片?
(1)[1,2,3,4,5,6,7,8,9]
(2)[1,2,3,4,5,6]
(3)[3,4,5,6]
(4)[9]
(5)[1,3,5,7,9]
1、[1:] 2、[1:7] 3、[3:7] 4、[-1] 5、[1::2]
4、有这样一段代码
a = 10
b = 20
c = [a]
a = 15
print c 会输出什么,为什么?
对于字符串、数字,传递是相应的值
5、for i in range(1):print i
for i in xrange(1):print i 这两段代码输出一样么,占用系统资源一样么,什么时候要用xrange代替range?
6、有这样一个url,foobar/homework/2009-10-20/xiaoming,其中2009-10-20和小明是变量,请用正则表达式捕获这个url,要求尽量准确
str1 = 'foobar/homework/2009-10-20/xiaoming' url_compile = re.compile('foobar/homework/(?P<date>\d{4}-\d{1,2}-\d{1,2})/(?P<username>\w+)') result = re.search(url_compile,str1) print(result.group('date')) print(result.group('username'))
7、有这样一个文本文件,他的路径为baseDir,他的名字test.txt,要求with方式打开,并打印每一行文本,并要求文件路径考虑跨平台问题
import os baseDir = r'C:\Users\haora' filename = 'test.txt' file_path = os.path.join(baseDir,filename) with open(file_path,'r') as f: for line in f.readlines(): print(line)
8、有processFunc变量,初始化为processFunc = collapse and (lambda s:" ".join(s.split())) or (lambda s:s)
调用上下文如下
collapse = True
processFunc = collapse and (lambda s:" ".join(s.split())) or (lambda s:s)
print processFunc('I\tam\ntest\tobject!')
collapse = False
processFunc = collapse and (lambda s:" ".join(s.split())) or (lambda s:s)
print processFunc('I\tam\ntest\tobject!')
I am test object!
I am
test object!