常見python面試題-手寫代碼系列


 

1.如何反向迭代一個序列

#如果是一個list,最快的方法使用reverse
tempList = [1,2,3,4]
tempList.reverse()
for x in tempList:
   print x

 

#如果不是list,需要手動重排
templist = (1,2,3,4)
for i in range(len(templist)-1,-1,-1):
   print templist[i]

2.如何查詢和替換一個文本中的字符串

#最簡單的方法使用replace()
tempstr = "hello you hello python are you ok"
print tempstr.replace("you","python")

 

#還可以使用正則,有個sub()
tempstr = "hello you hello python are you ok"
import re
rex = r'(hello|Use)'
print re.sub(rex,"Bye",tempstr)

3.使用python實現單例模式

#方法一:可以使用__new__方法
#在__new__方法中把類實例綁定到類變量_instance上,如果cls._instance為None表示該類還沒有實例化過,實例化該類並返回。如果cls_instance不為None表示該類已實例化,直接返回cls_instance
class SingleTon(object):
   def __new__(cls,*args,**kwargs):
       if not hasattr(cls,'_instance'):
           cls._instance = object.__new__(cls,*args,**kwargs)
       return cls._instance
class TestClass(SingleTon):
   a = 1

test1 = TestClass()
test2 = TestClass()
print test1.a,test2.a

test1.a=2
print test1.a,test2.a

print id(test1),id(test2)

 

#方法二:使用裝飾器,建立過實例的就放到instances里面,下次建立的時候先檢查里面有沒有
def SingleTon(cls,*args,**kwargs):
   instances = {}
   print instances
   def _singleton():
       if cls not in instances:
           instances[cls] = cls(*args,**kwargs)
       print instances
       return instances[cls]
   return _singleton

@SingleTon
class LastClass(object):
   a = 1
test1 = LastClass()
print test1.a
test2 = LastClass()
print test2.a

 

#方法三:使用__metaclass__(元類)關於元類看看這個吧;http://blog.jobbole.com/21351/
class SignalTon(type):
   def __init__(cls,name,bases,dict):
       super(SignalTon, cls).__init__(name,bases,dict)
       cls._instance = None

   def __call__(cls, *args, **kwargs):
       if cls._instance is None:
           cls._instance = super(SignalTon,cls).__call__(*args,**kwargs)
       return cls._instance

class TestClass(object):
   __metaclass__ = SignalTon

test1 = TestClass()
test2 = TestClass()

test1.a = 2
print test1.a,test2.a
print id(test1),id(test2)

 

#方法四:共享屬性  所謂單例就是所有的引用(實例,對象)擁有相同的屬性和方法,同一個類的實例天生都會有相同的方法,那我們只需要保證同一個類所產生的實例都具有相同的屬性。所有實例共享屬性最簡單直接的方法就是共享__dict__屬性指向。

class SingleTon(object):
   _state = {}
   def __new__(cls, *args, **kwargs):
       obj = object.__new__(cls,*args,**kwargs)
       obj.__dict__ = cls._state
       return obj

class TestClass(SingleTon):
   a = 1

test1 = TestClass()
test2 = TestClass()
print test1.a,test2.a
test1.a = 2
print test1.a,test2.a
print id(test1),id(test2)
#方法五:使用同一個模版
#寫在mysingleton.py中
class My_Singleton(object):
   def foo(self):
       pass

my_singleton = My_Singleton()

#寫在要使用這個實例的py文件里面,在不同的引用的地方都引用相同的實例,以此實現單例模式
from mysingleton import my_singleton
my_singleton.foo()

4.重新實現str.strip()

def rightStrip(tempStr,splitStr):
   endindex = tempStr.rfind(splitStr)
   while endindex != -1 and endindex == len(tempStr) - 1:
        tempStr = tempStr[:endindex]
        endindex = tempStr.rfind(splitStr)
   return tempStr

def leftStrip(tempStr,splitStr):
   startindex = tempStr.find(splitStr)
   while startindex == 0:
       tempStr = tempStr[startindex+1:]
       startindex = tempStr.find(splitStr)
   return tempStr

str = "  H  "
print str
print leftStrip(str,' ')
print rightStrip(str,' ')
#輸出
 H  
H  
 H

5.super的原理

#閱讀下面的代碼,它的輸出結果是什么?
class A(object):
 def __init__(self):
  print "enter A"
  super(A, self).__init__()  # new
  print "leave A"

class B(object):
 def __init__(self):
  print "enter B"
  super(B, self).__init__()  # new
  print "leave B"

class C(A):
 def __init__(self):
  print "enter C"
  super(C, self).__init__()
  print "leave C"

class D(A):
 def __init__(self):
  print "enter D"
  super(D, self).__init__()
  print "leave D"
class E(B, C):
 def __init__(self):
  print "enter E"
  super(E, self).__init__()  # change
  print "leave E"

class F(E, D):
 def __init__(self):
  print "enter F"
  super(F, self).__init__()  # change
  print "leave F"

#輸出

enter F
enter E
enter B
enter C
enter D
enter A
leave A
leave D
leave C
leave B
leave E
leave F

非常棒的講解:

http://www.cnblogs.com/lovemo1314/archive/2011/05/03/2035005.html

 

6.閉包

常用的裝飾器就是閉包的一種 

 

def make_adder(addend): 
   def adder(addend):
       return addend+addend
return adder

P1 = make_adder(5)
P2= make_adder(4)

print p1(10)
#輸出15
print p2(10)
#輸出14

 

閉包(Closure)是詞法閉包(Lexical Closure)的簡稱,是引用了自由變量的函數。這個被引用的自由變量將和這個函數一同存在,即使已經離開了創造它的環境也不例外 
http://www.cnblogs.com/ma6174/archive/2013/04/15/3022548.html

https://foofish.net/python-closure.html

7.給列表中的字典排序

list 對象 alist [{“name”:”a”,”age”:20},{“name”:”b”,”age”:30},{“name”:”c”,”age”:25}]按照 age 從大到小排序

alist = [{"name":"a","age":20},{"name":"b","age":30},{"name":"c","age":25}]
alist.sort(key=lambda:x:-x.get("age"))
print alist

8.合並兩個列表排除重復元素

用簡潔的方法合並alist = [‘a’,’b’,’c’,’d’,’e’,’f’] 
blist = [‘x’,’y’,’z’,’e’,’f’]並且元素不能重復

alist = ['a','b','c','d','e','f']
blist = ['x','y','z','e','f']
def merge_list(*args):
   s = set()
   for i in args:
       s = s.union(i)
   print(s)
   return s

merge_list(alist,blist)

9.打亂一個排好序的列表

from random import shuffle
alist = range(10)
print(alist)
shuffle(alist)
print(alist)

10.簡單的實現一個棧結構 stack

class Stack(object):
   def __init__(self):
       self.value = []

   def push(self,x):
       self.value.append(x)

   def pop(self):
       self.value.pop()

stack = Stack()

stack.push(1)
stack.push(2)
stack.push(3)
print(stack.value)
stack.pop()
print(stack.value)

11.輸入一個日期,返回時一年中的哪一天

from datetime import datetime
def which_day(year,month,day):
   return (datetime(year,month,day)-datetime(year,1,1)).days+1

print(which_day(2017,1,15))

12.把字符串”k1:1|k2:2|k3:3”處理成 python 字典的形式:{k1:1,k2:2,k3:3}

def string_to_dict(string):
   d = {}
   for kv in string.split("|"):
       k,v = kv.split(":")
       if v.isdigit():
           v=int(v)
       d[k]=v
   return d

print(string_to_dict("k1:1|k2:2|k3:3"))

13.判斷輸入的值是否在矩陣之中(楊氏矩陣)

在一個二維數組之中,每一行都按照從走到右遞增的順序排序,每一列到按照從上到下的順序排序.請完成一個函數,輸入這樣的一個二維手術和一個整數,判斷數組中是否含有該整數

#處理數組矩陣
arr = [[1,4,7,10,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]]
def get_num(num,data=None):
   while data:
       if num > data[0][-1]:
           del data[0]
       elif num<data[0][-1]:
           data = list(zip(*data))
           del data[-1]
           data = list(zip(*data))
       else:
           return True
           data.clear()
   return False
print (get_num(18,arr))

不處理數組矩陣 
使用 step-wise 線性搜索

def getvalue(data,value):
   m = len(data)-1
   n = len(data[0])-1
   r = 0
   c = n
   while c>=0 and r<=m:
       if value == data[r][c]:
           return True
       elif value>data[r][c]:
           r = r+1
       else:
           c = c-1
   return False

14.獲取最大公約數(歐幾里得算法)

a= 25
b=15

def max_common(a,b):
   while b:
       a,b=b,a%b
   return a

詳解:

https://blog.csdn.net/franktan2010/article/details/38229641

15.求兩個數的最小公倍數(公式法)

兩個數的乘積等於這兩個數的 最大公約數與最小公倍數的積

a=25
b=15
def min_common(a,b):
   c= a*b
   while b:
       a,b=b,a%b
   return c//a

詳情:

https://zhidao.baidu.com/question/90232880

16.獲取中位數

如果總數個數是奇數,按從小到大的順序,取中間的那個數;如果總數個數是偶數個的話,按從小到大的順序,取中間那兩個數的平均數。

#計算中位數
def mediannum(num):
   listnum = [num[i] for i in range(len(num))]
   listnum.sort()
   lnum = len(num)
   if lnum % 2 == 1:
       i = int((lnum + 1) / 2)-1
       return listnum[i]
   else:
       i = int(lnum / 2)-1
       return (listnum[i] + listnum[i + 1]) / 2

詳情:

https://blog.csdn.net/qq_33363973/article/details/78773144

def medin(data):
   data.sort()
   half = len(data)//2
   return (data[half]+data[~half])/2
l = [1,3,4,53,2,46,8,42,82]
print (median(l))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM