import time
import os
import sys
def log(fun):
def wrapper(*args,**kwargs):
result = fun(*args,**kwargs)
now_time = time.ctime()
#name = platform.uname.nodename.split('.')[0]
process_full_name = sys.argv[0]
process_name = os.path.split(process_full_name)[-1]
info = "函数[%s]的运行结果为%s" % (fun.__name__, result)
log = " ".join([now_time,process_name, info])
print(log)
with open('file.log', 'w') as f:
f.writelines(log)
return result
return wrapper
@log
def roll(name, age, **kwargs):
print(name, age, kwargs)
roll(name='陈辉', age=10, province='陕西', gender='男')
二、斐波那契数列装饰器练习:实现高速缓存递归
import time
import os
import json
def num_cache(fun):
list_info = {}
cache_filename = 'cache.txt'
if os.path.exists(cache_filename):
with open(cache_filename) as f:
try:
list_info = json.load(f)
except:
list_info = {}
def wrapper1(num):
if num in list_info:
result = list_info.get(num)
return result
else:
result = fun(num)
list_info[num] = result
return result
return wrapper1
def timeit(fun):
def wrapper2(*args):
start_time = time.time()
result = fun(*args)
end_time = time.time()
print('所用时间为%s' % (end_time - start_time))
return result
return wrapper2
@num_cache
def fib(n):
if n < 3:
return 1
else:
return fib(n-1) + fib(n-2)
@timeit
def fun1():
result = fib(200)
print('fib(200)=%s'%(result))
@timeit
def fun2():
result = fib(201)
print('fib(201)=%s'%(result))
fun1()
fun2()
三、Leetcode字符串练习题
def fun(v1,v2):
l_1 = v1.split('.')
l_2 = v2.split('.')
c = 0
while True:
if c == len(l_1) and c == len(l_2):
return 0
if len(l_1) == c:
l_1.append(0)
if len(l_2) == c:
l_2.append(0)
if int(l_1[c]) > int(l_2[c]):
return 1
elif int(l_1[c]) < int(l_2[c]):
return -1
c += 1
f = fun('0.1','1.1')
print(f)
四、微信好友数据分析与展示
import itchat
itchat.auto_login(False)
itchat.login()
my_friends = itchat.get_friends(update=True)[0:]
def province(Province):
area = {}
try:
for friend in my_friends[1:]:
area = friend[Province]
if area == '':
pass
elif area not in area.keys():
area[area] = 1
else:
area[area] += 1
return area
except:
print('请输入正确参数:')
print(area)
province(Province='陕西')
from pyecharts import Line
# 绘制柱状图
from pyecharts import Bar
# 创建条形图对象
bar = Bar("好友省份分布")
# 添加条形图绘制的信息
bar.add("", list(sortedFriend.keys()), list(sortedFriend.values()))
# 将绘制的图形保存未html文件, 默认存储于当前目录所再文件render.html
bar.render('doc/province.html')