1 利用切片操作,實作一個trim()函式,去除字串首尾的空格,注意不要呼叫str的strip()方法.
正解1:
def trim(s):
while s[:1] == ' ':
s = s[1:]
while s[-1:] == ' ':
s = s[:-1]
return s
正解2:
def trim(s):
if s[:1] == ' ':
s = trim(s[1:])
if s[-1:] == ' ':
s = trim(s[:-1])
return s
容易寫錯的方法:
def trim(s):
while s[0] == ' ':
s = s[1:]
while s[-1] == ' ':
s = s[:-1]
return s
解釋:當s=''時,s[0]和s[-1]會報IndexError: string index out of range,但是s[:1])和s[-1:]不會,
2 請設計一個decorator,它可作用于任何函式上,并列印該函式的執行時間.
# -*- coding: utf-8 -*-
import time, functools
def metric(fn):
@functools.wraps(fn)
def wrapper(*args, **kw):
time0 = time.time()
ret = fn(*args, **kw)
time1 = time.time()
print('%s executed in %s ms' % (fn.__name__, time1-time0))
return ret
return wrapper
3 裝飾器的實質是什么?或者說為什么裝飾器要寫2層嵌套函式,里層函式完全就已經實作了裝飾的功能為什么不直接用里層函式名作為裝飾器名稱?
答:裝飾器是要把原來的函式裝飾成新的函式,并且回傳這個函式本身的高階函式
本文首發于Python黑洞網,博客園同步跟新
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/185745.html
標籤:Python
上一篇:Git 程式員篇
下一篇:關于淺copy和深copy的理解
