python练习代码

排序

----------------------------------------------------------------

lst = [5,10,2,4,8,1]

def sort(item,reverse=False):
ret = []
for i in item:
for x,y in enumerate(ret): #[10,5]
flage=i>y if reverse else i<y
if flage:
ret.insert(x,i)
break
else:
ret.append(i)
return ret

*************
lst = [5,10,2,4,8,1]

def sort(item,reverse=True):
ret = []
def choise(a,b):
flage = a > b if reverse else a < b
return flage
for i in item:
for x,y in enumerate(ret): #[10,5]
if choise(i,y):
ret.insert(x,i)
break
else:
ret.append(i)
return ret
print(sort(lst))
*************
def choise(a, b,reverse):
flage = a > b if reverse else a < b
return flage

lst = [5,10,2,4,8,1]
def sort(item,reverse=False):
ret = []
for i in item:
for x,y in enumerate(ret): #[10,5]
if choise(i,y,reverse):
ret.insert(x,i)
break
else:
ret.append(i)
return ret
print(sort(lst))

------------------------------------------------
装饰器
import time
import datetime

def copy_property(src):
def warpper(dst):
dst.__name__ =src.__name__
dst.__doc__ =src.__doc__
return dst
return warpper


def logger(t):
def _logger(fn):
@copy_property(fn)
def wrapper(*args,**kwargs):
'''这是一个测试'''
start =datetime.datetime.now()
time.sleep(5)
result =fn(*args,**kwargs)
differ =(datetime.datetime.now() - start).total_seconds()
if differ > t:
print("用时:{}".format(differ))
return result
return wrapper
return _logger

@logger(6)
def add(x,y):
'''
:param x:
:param y:
:return:
'''
ret =x+y
return ret

print(add(3,9),add.__doc__,sep="\n")
---------------------------------------
递归
source  ={'a':{'b':1,'c':2}}

def flatmap(src):
def _flatmap(src,dest=None,pre=''):
for k,v in src.items():
key =pre+k
if isinstance(v,(list,dict,tuple,set)):
_flatmap(v,dest,pre=pre+k+'.')
else:
dest[key] =v

dest = {}
_flatmap(src,dest)
return dest

print(flatmap(source))
----------------------------
查找最长因子
str_1   ="afdscvasdf"
str_2 ="dfasdfdf"

def findstr(str1,str2):
length =len(str1)
for i in range(length,0,-1):
for x in range(0,length-i+1):
substr =str1[x:x+i]
if str2.find(substr) > -1:
return substr

print(findstr(str_1,str_2))



posted @ 2020-01-13 20:35  冬日的温暖  阅读(319)  评论(0编辑  收藏  举报