您的位置:首页 > 编程语言 > Python开发

python 常见面试问题(3)-单例模式/lambda函数/类型转换/文件操作/查询和替换/Fibonacci数列

2012-12-14 17:24 609 查看
1:Python如何实现单例模式?

单例模式的意思就是只有一个实例。单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。这个类称为单例类

显然单例模式的要点有三个;一是某个类只能有一个实例;二是它必须自行创建这个实例;三是它必须自行向整个系统提供这个实例。在下面的对象图中,有一个"单例对象",而"客户甲"、"客户乙" 和"客户丙"是单例对象的三个客户对象。可以看到,所有的客户对象共享一个单例对象。而且从单例对象到自身的连接线可以看出,单例对象持有对自己的引用。

Python有两种方式可以实现单例模式,下面两个例子使用了不同的方式实现单例模式:

1.

class Singleton(type):

def __init__(cls, name, bases, dict):

super(Singleton, cls).__init__(name, bases, dict)

cls.instance = None

def __call__(cls, *args, **kw):

if cls.instance is None:

cls.instance = super(Singleton, cls).__call__(*args, **kw)

return cls.instance

class MyClass(object):

__metaclass__ = Singleton

print MyClass()

print MyClass()

2. 使用decorator来实现单例模式

def singleton(cls):

instances = {}

def getinstance():

if cls not in instances:

instances[cls] = cls()

return instances[cls]

return getinstance

@singleton

class MyClass:



2:什么是lambda函数?

Python允许你定义一种单行的小函数。定义lambda函数的形式如下:

labmda 参数:表达式lambda函数默认返回表达式的值。

你也可以将其赋值给一个变量。lambda函数可以接受任意个参数,包括可选参数,但是表达式只有一个:

>>> g = lambda x,y:x*y
>>> g(3,4)
12
>>> g = lambda x,y,z:x*y+z
>>> g(3,4,5)
17
>>> (lambda x,y,z:x*y+z)(3,4,5)           #直接使用lambda函数,不把它赋值给变量
17
>>>
函数非常简单,只有一个表达式,不包含命令,可以考虑lambda函数。否则,你还是定义函数才对,毕竟函数没有这么多限制。

3:Python是如何进行类型转换的?

Python提供了将变量或值从一种类型转换成另一种类型的内置函数。int函数能够将符合数学格式数字型字符串转换成整数。否则,返回错误信息。

>>> int(23)
23
>>> int('23')  #字符转换成整形
23
>>> int('bc')   #无法转换字符串
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'bc'
>>> int('23.45')     #无法转换浮点型的字符串
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '23.45'
>>> float('23.45')    #字符串转换成浮点型
23.449999999999999
>>> float(23.45)      #
23.449999999999999
>>> float(23)        #整形转换成浮点型
23.0
>>> int(-23.45)    #对负数转换
-23
>>> str(98)        #数字型转换成字符,反转;
'98'
>>> str(98.4343)
'98.4343'
>>>
4、Python如何定义一个函数

函数的定义形式如下:

def function(arg1, arg2,… argN):

函数的名字也必须以字母开头,可以包括下划线“ ”,但不能把Python的

关键字定义成函数的名字。函数内的语句数量是任意的,每个语句至少有

一个空格的缩进,以表示此语句属于这个函数的。缩进结束的地方,函数

自然结束。

>>> def addtion(a,b):
...     print "a + b=",a+b
...
>>> addtion (5,6)
a + b= 11
>>>
函数的目的是把一些复杂的操作隐藏,来简化程序的结构,使其容易

阅读。函数在调用前,必须先定义。也可以在一个函数内部定义函数,内

部函数只有在外部函数调用时才能够被执行。程序调用函数时,转到函数

内部执行函数内部的语句,函数执行完毕后,返回到它离开程序的地方,

执行程序的下一条语句。

5:Python是如何进行内存管理的?

Python的内存管理是由Python的解释器负责的,开发人员可以从内存管理事务中解放出来,致力于应用程序的开发,这样就使得开发的程序错误更少,程序更健壮,开发周期更短

6:如何反序的迭代一个序列?how do I iterate over a sequence in reverse order

如果是一个list, 最快的解决方案是:

list.reverse()

>>> ab = [1,2,3,4,5]
>>>
>>> ab.reverse()
>>> ab
[5, 4, 3, 2, 1]
>>> try:
...     for x in ab:
...             "do something with x"
... finally:
...     ab.reverse()
...
'do something with x'
'do something with x'
'do something with x'
'do something with x'
'do something with x'
>>> ab
[1, 2, 3, 4, 5]
>>>
如果不是list, 最通用但是稍慢的解决方案是:

for i in range(len(sequence)-1, -1, -1):

x = sequence[i]

>>> ab = (3,4,5,6)
>>> for i in range(len(ab)-1,-1,-1):
...     x = ab[i]
...     print x
...
6
5
4
3
7:Python里面如何实现tuple和list的转换?

函数tuple(seq)可以把所有可迭代的(iterable)序列转换成一个tuple, 元素不变,排序也不变。

例如,tuple([1,2,3])返回(1,2,3), tuple(’abc’)返回(’a’.’b’,’c’).如果参数已经是一个tuple的话,函数不做任何拷贝而直接返回原来的对象,所以在不确定对象是不是tuple的时候来调用tuple()函数也不是很耗费的。

>>> ab = (1,2,3,4)
>>> ab
(1, 2, 3, 4)
>>> bc = [2,3,4,5]
>>> bc
[2, 3, 4, 5]
>>> tuple(ab)
(1, 2, 3, 4)
>>> tuple(bc)
(2, 3, 4, 5)
>>> tuple('abcd')
('a', 'b', 'c', 'd')
>>>
函数list(seq)可以把所有的序列和可迭代的对象转换成一个list,元素不变,排序也不变。

例如 list([1,2,3])返回(1,2,3), list(’abc’)返回['a', 'b', 'c']。如果参数是一个list, 她会像set[:]一样做一个拷贝

>>> bc
[2, 3, 4, 5]
>>> list(bc)
[2, 3, 4, 5]
>>> list(ab)
[1, 2, 3, 4]
>>> list('abcd')
['a', 'b', 'c', 'd']
>>> ab
(1, 2, 3, 4)
>>>
8:请写出一段Python代码实现删除一个list里面的重复元素

可以先把list重新排序,然后从list的最后开始扫描,代码如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-
#filename :del_repetitive_list.py

ab = [3,4,5,6,6,4,7]
if ab:
ab.sort()
print "the sorted list is " ,ab
last = ab[-1]
for i in range(len(ab)-2,-1,-1):
if last == ab[i]:
del ab[i]
else:
last = ab[i]
print "the new list is",ab
>>> ================================ RESTART ================================
>>>
the sorted list is  [3, 4, 4, 5, 6, 6, 7]
the new list is [3, 4, 5, 6, 7]
>>>
9:Python文件操作题

1. 如何用Python删除一个文件?

使用os.remove(filename)或者os.unlink(filename);

yee@Loong:~$ ls
1.txt                                      lottery                  STUDENTCONFIG.ini
2.txt                                      ls


>>> import os
>>> os.remove('/home/yee/1.txt')  win下路径写法要注意:如:('E:\\book\\temp')
>>>
yee@Loong:~$ ls
2.txt                                      ls


2. Python如何copy一个文件?

shutil模块有一个copyfile函数可以实现文件拷贝

>>> import shutil
>>> shutil.copy('/home/yee/2.txt','/home/yee/shell')
>>>
yee@Loong:~$ ls shell/2.txt
ls: 无法访问 shell/2.txt: 没有那个文件或目录
yee@Loong:~$ ls shell/2.txt
shell/2.txt


shutil.copy(src,dst)
Copy the file src to the file or directory dst. If dst is a directory, afile with the same basename assrc is created (or overwritten) in thedirectory specified. Permission bits are copied.src anddst are
pathnames given as strings.

一般来说可以使用copy.copy()方法或者copy.deepcopy()方法,几乎所有的对象都可以被拷贝

一些对象可以更容易的拷贝,Dictionaries有一个copy方法:

newdict = olddict.copy()

10:Python里面如何生成随机数?

标准库random实现了一个随机数生成器,实例代码如下:

import random

random.random()

它会返回一个随机的0和1之间的浮点数

random.random()

Return the next random floating point number in the range [0.0, 1.0).
random.randrange(stop)
random.randrange(start, stop[, step])

Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn’t actually build
a range object.
>>> import random
>>> random.random()            #取0-1之间的随机浮点数;
0.95295129705871395
>>> random.random()
0.081778052552226699
>>> random.randrange(2,20,3) #  按一定步长随机取数
11
>>> random.randrange(2,20,3)
2
>>> random.randrange(2,20,3)
5
>>> random.randrange(2,20)
5
>>> random.randrange(2,20)
19
>>> random.randrange(2,20,4)
2
>>> random.randrange(2,20,4)
10
>>> random.choice('defgrttyu')  #随机取字符
't'
>>> random.choice('defgrttyu')
'r'
>>> random.sample([9,6,75,5,6,4,3],3)    #随机取指定长度的样本
[9, 6, 75]
>>> random.sample([9,6,75,5,6,4,3],3)
[75, 9, 6]
>>> random.sample([9,6,75,5,6,4,3],3)
[3, 75, 6]
>>> random.sample([9,6,75,5,6,4,3],3)
[5, 6, 75]
>>> items = [1, 2, 3, 4, 5, 6, 7]  #随机排序
>>> random.shuffle(items)
>>> items
[7, 3, 2, 5, 6, 4, 1]

random.uniform(a,b)
Return a random floating point number N such thata<=N<=b
fora<=b andb<=N<=a
forb<a.

The end-point value b may or may not be included in the rangedepending on floating-point rounding in the equationa+(b-a)*random().

11:有没有一个工具可以帮助查找python的bug和进行静态的代码分析?

有,PyChecker是一个python代码的静态分析工具,它可以帮助查找python代码的bug, 会对代码的复杂度和格式提出警告

Pylint是另外一个工具可以进行coding standard检查。

12:如何在一个function里面设置一个全局的变量?

解决方法是在function的开始插入一个global声明:

def f()

global x

13:Python里面search()和match()的区别?

match()函数只检测RE是不是在string的开始位置匹配, search()会扫描整个string查找匹配, 也就是说match()只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话,match()就返回none

例如:

print(re.match(’super’, ’superstition’).span())会返回(0, 5)

而print(re.match(’super’, ‘insuperable’))则返回None

search()会扫描整个字符串并返回第一个成功的匹配

例如:print(re.search(’super’, ’superstition’).span())返回(0, 5)

print(re.search(’super’, ‘insuperable’).span())返回(2, 7)

14:如何用Python来进行查询和替换一个文本字符串?

可以使用sub()方法来进行查询和替换,sub方法的格式为:sub(replacement, string[, count=0])

replacement是被替换成的文本

string是需要被替换的文本

count是一个可选参数,指最大被替换的数量

>>> p = re.compile('(blue|white|red)')
>>> print(p.sub('black','blue heavens'))
black heavens
>>> print(p.sub('black','blue heavens and red sun or white snow',count=1))
black heavens and red sun or white snow
>>> print(p.sub('black','blue heavens and red sun or white snow',count=2))
black heavens and black sun or white snow
>>> print(p.sub('black','blue heavens and red sun or white snow',count=3))
black heavens and black sun or black snow

subn()方法执行的效果跟sub()一样,不过它会返回一个二维数组,包括替换后的新的字符串和总共替换的数量

>>> print(p.subn('black','blue heavens and red sun or white snow',count=3))
('black heavens and blacksun or black snow', 3)
15:介绍一下except的用法和作用?(前一篇文章也有例子)

Python的except用来捕获所有异常, 因为Python里面的每次错误都会抛出 一个异常,所以每个程序的错误都被当作一个运行时错误。

一下是使用except的一个例子:

try:

foo = opne(”file”) #open被错写为opne

except:

sys.exit(”could not open file!”)

因为这个错误是由于open被拼写成opne而造成的,然后被except捕获,所以debug程序的时候很容易不知道出了什么问题

下面这个例子更好点:

try:

foo = opne(”file”) # 这时候except只捕获IOError

except IOError:

sys.exit(”could not open file”)

16:Python中pass语句的作用是什么?

pass语句什么也不做,一般作为占位符或者创建占位程序,pass语句不会执行任何操作,比如:

while False:

pass

pass通常用来创建一个最简单的类:

class MyEmptyClass:

pass

pass在软件设计阶段也经常用来作为TODO,提醒实现相应的实现,比如:

def initlog(*args):

pass #please implement this

17:介绍一下Python下range()函数的用法?

如果需要迭代一个数字序列的话,可以使用range()函数,range()函数可以生成等差级数。

如例:

for i in range(5)

print(i)

这段代码将输出0, 1, 2, 3, 4五个数字

range(10)会产生10个值, 也可以让range()从另外一个数字开始,或者定义一个不同的增量,甚至是负数增量

range(5, 10)从5到9的五个数字

range(0, 10, 3) 增量为三, 包括0,3,6,9四个数字

range(-10, -100, -30) 增量为-30, 包括-10, -40, -70

可以一起使用range()和len()来迭代一个索引序列

例如:

a = ['Nina', 'Jim', 'Rainman', 'Hello']

for i in range(len(a)):

print(i, a[i])

ab = [3,4,5,6,6,4,7]
if ab:
for i in range(len(ab)):
print (i,ab[i])
>>>
(0, 3)
(1, 4)
(2, 5)
(3, 6)
(4, 6)
(5, 4)
(6, 7)
>>>

18、用Python输出一个Fibonacci数列?

>>> a,b = 0,1
>>> while b < 100:
...     print(b)
...     a,b = b, a+b
...
1
1
2
3
5
8
13
21
34
55
89
>>>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: