# 函数编程 - 考核题

2018/03/06 17:48

# -*- coding:utf-8 -*-
# 考核
# 1.有如下字符串：n = "路飞学城"（编程题）
# - 将字符串转换成utf-8的字符编码的字节，再将转换的字节重新转换为utf-8的字符编码的字符串
# - 将字符串转换成gbk的字符编码的字节，再将转换的字节重新转换为utf-8的字符编码的字符串
# n = '路飞学诚'
# print(n.encode('utf-8'))
# print(n.encode('utf-8').decode('utf-8'))
# print(n.encode('gbk'))
# print(n.encode('gbk').decode('gbk').encode('utf-8').decode('utf-8'))

# 2.读文件找到第9个字符，华 ，找到第二行的 实，删除最后一行 写入文件
# 桃之夭夭，灼灼其华。之子于归，宜其室家。
# 桃之夭夭，有蕡其实。之子于归，宜其家室。
# 桃之夭夭，其叶蓁蓁。之子于归，宜其家人。
# f = open('ee.txt', 'r+', encoding='utf-8')
# f.seek(3*8)
# f.seek(3*28+2)
# data_list.pop()
# f.seek(0)
# f.truncate()
# f.write(''.join(data_list))

# 3.求出函数的执行时间 利用装饰器
# import time
#
# def time_fun(func):
# def inner(*args, **kwargs):
# time_start = time.time()
# func(*args, **kwargs)
# time_end = time.time()
# print(time_end - time_start)
# return inner
#
# @time_fun
# time.sleep(2)
# return x+y
#

# 带参数的装饰器
# import time
# def time_fun(type):
# def outter(func):
# def inner(*args, **kwargs):
# time_start = time.time()
# func(*args, **kwargs)
# time_end = time.time()
# print(time_end - time_start)
# return inner
# return outter
#
#
# @time_fun('ok')
# time.sleep(2)
# return x+y
#

# 4.作用域
# def test():
# print(luffy)
#
# luffy = "the king of sea."
# test()

# def test(): # 函数一旦定义 作用域就已经生成
# print(luffy)
# luffy = 'e'
#
# luffy = "the king of sea."
# test()

# 5.li = [1,2,3,5,5,6,7,8,9,9,8,3] 利用生成器功能，写一个所有数值乘以2的功能
# li = [1,2,3,5,5,6,7,8,9,9,8,3]
# res = (i*2 for i in li)
# print(next(res))
# print(res.__next__())
# for i in res:
# print(i)

# def fun(li):
# for i in li:
# n = i*2
# yield n
#
# res = fun(li)
# print(next(res))
# print(res.__next__())

# 6.打印日志11/26/2017 10:44:21 PM bug 24 并写入文件example.log中
# import logging
# logging.basicConfig(filename='example.log', format='%(asctime)s - %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG)
# logging.warning('bug 24')

# ------------练习start----------------------------
# 1.json 和 pickle
# import json,pickle # json 可序列化的有 int str list tuple dict 没有集合 pickle 可序列化python所有数据类型包括函数 pickle 可序列化一些类 但类需要引用
# li = [1,2,3]
# li = {1,2,3}
# def fun():
# return 3
# str_data = json.dumps(li)
# print(type(str_data),str_data)
# print(list_data[2])
# s = pickle.dumps(li)
# print(s)
# print(data)
# with open('test.txt','w',encoding='utf-8') as f:
# json.dump(li,f)
# print(data,type(data))
# pickle.dump(li,open('test1.txt','wb'))
# print(data,type(data))
# pickle.dump(fun,open('test2.txt','wb'))
# print(data())

# 2.闭包
# def fun1():
# n = 10
# def fun2():
# return n
# return fun2
# f=fun1()
# print(f())

# 3.生成器 迭代器 斐波那契数列 #可迭代对象有 str 列表 元组 字典 集合 yield函数
# s = (i for i in range(10))
# print(next(s))
# def fun(n):
# x=0
# while(x<n):
# yield x
# x+=1
# s = fun(3)
# print(next(s))
# print(s.__next__())
# from collections import Iterable,Iterator
# print(isinstance({1,2,3},Iterable))
# s = iter([1,2,3,4,3,2,1])
# print(s.__next__())
# print(next(s))
# for i in s:
# print(i)

# 斐波那契数列（Fibonacci）
# 1,1,2,3,5,8,13,21,34,... 除第一个和第二个外，任何一个数都由前两个数相加
# def fun(x):
# n, a, b = 0, 0, 1
# while n < x:
# yield b
# a, b = b, a + b
# n += 1
#
# res = fun(10)
# for i in res:
# print(i)
# while True:
# print(next(res))

# 4. map filter globals() locals() hash()
# print(globals())
# print(locals())
# n1=[1,2,3]
# def fun():
# n1[1] ='123'
# print(n1)
# fun()
# print(n1)
# res = map(lambda x:x*2,[1,2,3])
# for i in res:
# print(i)
# res = filter(lambda x:x%2==0,list(range(10)))
# for i in res:
# print(i)
# print(res.__next__())
# print(next(res))
# print(hash((1,2,3))) # 只有 不可变的才可哈希 int str tuple 如：list dict set 不能被哈希

# 5. 三目 匿名 lambda
# a = 2
# b = 5
# print(a if a>b else b)
# print(lambda a if a>b else b)
# fun = lambda x,y:x+y
# fun = lambda x,y:x if x>y else y
# print(fun(2,3))
# res = map(lambda x:x*x,list(range(10)))
# for i in res:
# print(i)
# fun = lambda x,y:x/y if x>y else x*y
# print(fun(4,3))

# 6.time datetime,random,
# import time,datetime,random
# print(time.time())
# print(time.asctime())
# print(time.gmtime())
# print(time.strftime('%Y-%m-%d %I:%M:%S %p',time.localtime()))
# str_time =time.strftime('%Y-%m-%d %I:%M:%S %p',time.localtime())
# print(str_time)
# res = time.strptime(str_time,'%Y-%m-%d %I:%M:%S %p')
# print(res)
# print(time.mktime(res))
# res =datetime.datetime.now() + datetime.timedelta(days=2,hours=3)
# print(res)
# res1 = datetime.datetime.now().replace(year=2015,month=2,day=2)
# print(res1)
# print(datetime.date.fromtimestamp(time.time()))
# print(random.randint(1,3)) # 会包含3
# print(random.randrange(1,3)) # 不会包含3
# print(random.random())
# print(random.choice('123123'))
# import string
# print(''.join(random.sample(string.digits+string.punctuation+string.ascii_letters,6)))
# li = list(range(10))
# random.shuffle(li)
# print(li)

# 7.os sys
# import os,sys
# print(os.getcwd())
# print(os.listdir())
# print(os.environ)
# os.path.isfile()
# os.path.isdir()
# os.path.isabs()
# os.path.exist()
# print(os.path.split(__file__))
# print(os.path.splitext(__file__))
# print(os.path.dirname(__file__))
# print(os.getcwd())
# print(os.path.basename(__file__))
# print(os.path.abspath(__file__))
# print(os.path.getsize(__file__))
# print(os.path.join(os.getcwd(),'test.py'))
# print(sys.path)
# sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

# ------------练习end----------------------

# 考核
# 1.作用域 范围
# x = 10
# return a + b
#
# print(ret) # 输出 20
#
# x = 20
# print(ret) # 输出 20 不是30 注意模块执行的流程 从上到下

# 2.lambda 的应用
# # ---CASE 1
# fs = map(lambda i:(lambda j: i*j), range(6))
# print([f(2) for f in fs])
#
# #---CASE 2
# fs = [lambda j:i*j for i in range(6)]
# print([f(2) for f in fs])
#
# #---CASE 3
# fs = []
# for i in range(6):
# fs.append(lambda j:i*j)
# if i==3:
# break
# print([f(2) for f in fs])
#
# #---CASE 4
# fs = [(lambda i:lambda j:i*j)(i) for i in range(6)]
# print([f(2) for f in fs])

# 参考lambda的应用： www.cnblogs.com/xiangnan/p/3900285.html?utm_source=tuicool&utm_medium=referral

# 3.带参数的装饰器
# import time
# from functools import wraps
#
# def time_fun(type):
# def outter(func):
# def inner(*args, **kwargs):
# time_start = time.time()
# func(*args, **kwargs)
# time_end = time.time()
# print(time_end - time_start)
# return inner
# print(type)
# return outter
#
#
# @time_fun('ok')
# # <function time_fun.<locals>.outter.<locals>.inner at 0x00000158C9810BF8>
# # <function add at 0x000001B9CEBD0AE8>
# time.sleep(2)
# return x+y
#

0
0 收藏

0 评论
0 收藏
0