# 1. 返回函数、闭包
import functools
import time
def cal_sums(*args):
def do_sum():
result = 0
for x in args:
result += x
return result
return do_sum
call_sum = cal_sums(1, 3, 5, 7, 9)
call_sum_two = cal_sums(1, 3, 5, 7, 9)
print(call_sum)
print(call_sum_two)
print(call_sum())
def count():
fs = []
for i in range(1, 4):
def f():
return i * i
fs.append(f)
return fs
f1, f2, f3 = count()
print(f1)
print(f1(), f2())
def count_two():
fs = []
def g(j):
def f():
return j * j
return f
for i in range(1, 4):
fs.append(g(i))
return fs
f4, f5, f6 = count_two()
print(f4(), f5(), f6())
# 练习 利用闭包返回一个计数器函数,每次调用它返回递增整数:
def createCounter():
x = 0
def counter():
nonlocal x
x += 1
return x
return counter
# 测试:
counterA = createCounter()
print(counterA(), counterA(), counterA(), counterA(), counterA()) # 1 2 3 4 5
counterB = createCounter()
if [counterB(), counterB(), counterB(), counterB()] == [1, 2, 3, 4]:
print('测试通过!')
else:
print('测试失败!')
# 2. 匿名函数
l = list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
print(l)
# 练习
# 请用匿名函数改造下面的代码:
def is_odd(n):
return n % 2 == 1
L = list(filter(is_odd, range(1, 20)))
M = list(filter(lambda x: x % 2 == 1, range(1, 20)))
print(M)
# 3. 装饰器
def print_date():
print('2022-07-10')
f = print_date
print(print_date.__name__)
print(f.__name__)
def log(func):
def wrapper(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return wrapper
@log
def print_date():
print('2022-07-10')
print_date()
@log
def print_sth(str):
print(str)
return "print_sth_return"
p_r = print_sth("print-something")
print(p_r)
print(print_sth.__name__)
def log_fun_name(func):
@functools.wraps(func)
def wrapper(*args, **kw):
print('call %s():' % func.__name__)
return func(*args, **kw)
return wrapper
@log_fun_name
def print_sth(str):
print(str)
return "print_sth_return"
p_r = print_sth("print-something")
print(p_r)
print(print_sth.__name__)
# 练习 1.请设计一个decorator,它可作用于任何函数上,并打印该函数的执行时间:
def metric(fn):
@functools.wraps(fn)
def wrapper(*args, **kvs):
start_time = time.time()
result = fn(*args, **kvs)
end_time = time.time()
print('%s executed in %s ms' % (fn.__name__, end_time - start_time))
return result
return wrapper
# 测试
@metric
def fast(x, y):
time.sleep(0.0012)
return x + y;
@metric
def slow(x, y, z):
time.sleep(0.1234)
return x * y * z;
f = fast(11, 22)
s = slow(11, 22, 33)
if f != 33:
print('测试失败!')
elif s != 7986:
print('测试失败!')
# 练习2. 请编写一个decorator,能在函数调用的前后打印出'begin call'和'end call'的日志。
#
# 再思考一下能否写出一个@log的decorator,使它既支持:
# @log
# def f():
# pass
# 又支持
# @log('execute')
# def f():
# pass
def log(*text):
print(text)
def wrapper(func):
def excute(*args, **kvs):
print("Text:", text, "Length", len(text))
print("begin call")
result = func(*args, **kvs)
print("end call")
return result
return excute
return wrapper
@log("execute", "exg", "abcd")
def f():
return "Have Args"
print(f())
@log()
def f():
return "No args"
print(f())
#4. 偏函数
int2 = functools.partial(int, base=2)
print(int2("10000"))
2022-06-20 python练习-函数式编程(一)
发表于
|
阅读次数
# 1. 高阶函数
from functools import reduce
f = abs
print(f)
print(f(-10))
def absadd(x, y, f):
return f(x) + f(y)
print(absadd(-3, -4, f))
# 2. map reduce
def fuc_square(x):
return x * x
r_m = map(fuc_square, [1, 2, 3, 4, 5])
print(list(r_m))
def red_fuc(x, y):
return x * 10 + y
r_r = reduce(red_fuc, [1, 3, 5, 7, 9])
print(r_r)
# 练习 1
# 利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。
# 输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']:
def normalize(name):
return str.capitalize(name)
L1 = ['adam', 'LISA', 'barT']
L2 = list(map(normalize, L1))
print(L2)
# 练习 2
# Python提供的sum()函数可以接受一个list并求和,
# 请编写一个prod()函数,可以接受一个list并利用reduce()求积:
def prod(L):
def multi(x, y):
return x * y
return reduce(multi, L)
print('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))
if prod([3, 5, 7, 9]) == 945:
print('测试成功!')
else:
print('测试失败!')
# 练习 3
# 利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456
def str2float(s):
dic = {"1": 1, "2": 2, "3": 3, ".": ".", "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9}
point = -1
def map_fuc(x):
return dic[x]
def reduce_fuc(x, y):
# 作用域上溯一层
nonlocal point
if y == ".":
point = 1
return x
elif point == -1:
return x * 10 + y
else:
point *= 10
return x + y / point
list_nums = list(map(map_fuc, s))
print(list_nums)
return reduce(reduce_fuc, list_nums)
print('str2float(\'123.456\') =', str2float('123.456'))
if abs(str2float('123.456') - 123.456) < 0.00001:
print('测试成功!')
else:
print('测试失败!')
# 3. filter
def is_odd(n):
return n % 2 == 1
print(list(filter(is_odd, list(range(1, 11)))))
# 练习 生成质数数列
def odd_gen():
n = 1
while True:
n += 2
yield n
def not_divisible(n):
return lambda x: x % n > 0
def primes():
yield 2
it = odd_gen()
while True:
n = next(it)
yield n
it = filter(not_divisible(n), it)
# 打印1000以内的素数:
for n in primes():
if n < 1000:
print(n)
else:
break
c = not_divisible(3)
print(c(3))
# 练习 回数是指从左向右读和从右向左读都是一样的数,例如12321,909。请利用filter()筛选出回数:
def int_gen():
n = 1
while True:
yield n
n += 1
def is_palindrome(n):
if n < 10:
return True
if n % 10 == 0:
return False
temp = 0
while n > temp:
temp = temp * 10 + n % 10
n = int(n / 10)
return temp == n or int(temp / 10) == n
output = filter(is_palindrome, range(1, 1000))
print('1~1000:', list(output))
if list(filter(is_palindrome, range(1, 200))) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101,
111, 121, 131, 141, 151, 161, 171, 181, 191]:
print('测试成功!')
else:
print('测试失败!')
# 4. sort
print(sorted([36, 5, -12, 9, -21]))
print(sorted([36, 5, -12, 9, -21], key=abs))
print(sorted([36, 5, -12, 9, -21], key=abs, reverse=True))
# 练习 假设我们用一组tuple表示学生名字和成绩:
# L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
# 请用sorted()对上述列表分别按名字排序:
L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]
def by_name(t):
return t[0]
L2 = sorted(L, key=by_name)
print(L2)
# 再按成绩从高到低排序:
def by_score(t):
return t[1]
L2 = sorted(L, key=by_score, reverse=True
)
print(L2)
2022-06-07 python练习-高级特性
发表于
|
阅读次数
# 高级特性
# 1. 切片和列表生成器
from collections.abc import Iterable, Iterator
list_one = list(range(10))
print(list_one[:3])
print(list_one[2:7])
print(list_one[-5:-1])
# 取后5个数
print(list_one[-5:])
# 取偶数
print(list_one[:10:2])
# 取奇数
print(list_one[1:10:2])
# 字符串也可以切片
str_one = "My name is Yummy"
print(str_one[:5])
print(str_one[:10:3])
def trim_str(str):
result = str
if str[-1] == " ":
result = str[:-1]
return result
print(trim_str("Yummy ") + "!")
print(trim_str("Yummy") + "!")
# 2. 迭代
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print(key)
for v in d.values():
print(v)
for k, v in d.items():
print(k, v)
for s in "Yummy":
print(s)
print(isinstance(123, Iterable))
for i, value in enumerate(["A", "B", "C"]):
print(i, value)
for x, y in [(1, 2), (4, 6), (7, "A")]:
print(x, y)
# 测试
def findMinAndMax(param):
max, min = None, None
if param and param != []:
for v in param:
if max == None:
max = min = v
elif v > max:
max = v
elif v < min:
min = v
return (min, max)
if findMinAndMax([]) != (None, None):
print('测试失败!')
elif findMinAndMax([7]) != (7, 7):
print('测试失败!')
elif findMinAndMax([7, 1]) != (1, 7):
print('测试失败!')
elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
print('测试失败!')
else:
print('测试成功!')
# 3. 列表生成
list_two = [x * x for x in range(1, 11)]
print(list_two)
list_three = [x * x for x in range(1, 11) if x % 2 != 0]
print(list_three)
list_four = [m + n for m in "ABC" for n in "123"]
print(list_four)
d_str = {"A": "1", "B": "2", "C": "3"}
list_five = [k + "=" + v for k, v in d_str.items()]
print(list_five)
# 变成小写
print([v.lower() for v in list_five])
list_six = [x * x if x % 2 == 0 else -x for x in range(1, 11)]
print(list_six)
# 练习变小写,需要判断类型
L1 = ['Hello', 'World', 18, 'Apple', None]
L_output = [x.lower() if isinstance(x, str) else x for x in L1]
print(L_output)
# 4. 生成器
g = (x * x if x % 2 == 0 else -x for x in range(1, 11))
next(g)
print(next(g))
for v in g:
print(v)
def feb(max):
a, b, n = 0, 1, 0
while n < max:
a, b = b, a + b
yield a
n += 1
return "over"
fg = feb(10)
for v in fg:
print(v)
# 练习:生成器,杨辉三角形
# 1
# / \
# 1 1
# / \ / \
# 1 2 1
# / \ / \ / \
# 1 3 3 1
# / \ / \ / \ / \
# 1 4 6 4 1
# / \ / \ / \ / \ / \
# 1 5 10 10 5 1
def g_triangle():
last_row = [1]
cur_row = [1]
n = 0
while n < 10:
if n == 0:
cur_row = [1]
elif n == 1:
cur_row = [1, 1]
else:
idx = 1
while idx < n:
cur_row.append(last_row[idx - 1] + last_row[idx])
idx += 1
cur_row.append(1)
yield cur_row
last_row = cur_row
cur_row = [1]
n += 1
return
n = 0
results = []
for t in g_triangle():
results.append(t)
n = n + 1
if n == 10:
break
for t in results:
print(t)
if results == [
[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 4, 6, 4, 1],
[1, 5, 10, 10, 5, 1],
[1, 6, 15, 20, 15, 6, 1],
[1, 7, 21, 35, 35, 21, 7, 1],
[1, 8, 28, 56, 70, 56, 28, 8, 1],
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
]:
print('测试通过!')
else:
print('测试失败!')
#5. 迭代器 可以被next()函数调用并不断返回下一个值的对象称为迭代器
print(isinstance((x for x in range(10)), Iterator))
print(isinstance((x for x in range(10)), Iterable))
print(isinstance([], Iterator))
print(isinstance([], Iterable))
2022-05-19 python练习
发表于
|
阅读次数
# Python demo for lihz
# 1. Hello World
print("Hello World Python")
# 2. 输入输出
print("The quick brown fox", "jumps over the lazy dog")
print("100", "+", "200", "=", 100 + 200)
# name = input("What is your name ? \r\n")
# print("My name is",name)
print('''Line1
Line2
Line3''')
# 3. 字符串
print(chr(66))
print(chr(22334))
# bytes 数据类型
x = b'abc'
print(x)
print("中文".encode("utf-8"))
print(b'\xe4\xb8\xad\xe6\x96\x87'.decode("utf-8"))
print("My name is %s" % "OneCoder")
age = 38
print(f"My age is {age}")
# 4. list tuple
# list 有序集合
numbers = ["8676", "8616", "8385"]
print("The length of list numbers is %s" % len(numbers))
numbers.append("8528")
numbers.pop(1)
numbers.insert(1, "8448")
print(numbers)
# tuple 不可变元组
families = ("Dad", "Mum", "Son")
print(len(families))
one = (1,)
print(one)
print((1))
# 5. 判断和循环
number = 20
if int(number) > 18:
print(number)
elif int(number) > 6:
print("less than 18")
sum = 0
for x in range(101):
sum += x
print(sum)
# 6. dict即map和Set
d = {"Dad": 38, "Mum": 37}
print(d["Mum"])
print(d.get("Son", "Yummy"))
# set 元素不重复
s1 = set([1, 2, 3, 3])
print(s1)
s2 = set([2, 3, 4])
s1.add(5)
print(s1 & s2)
print(s1 | s2)
# 7. 函数
h = hex
print(h(12))
def print_name(name):
print("My name is", name)
def return_tuple():
return 12, 34
x, y = return_tuple()
print(x)
print(y)
print_name("Yummy")
def power(x, n=2):
s = 1
while n > 0:
s = s * x
n -= 1
return s
print(power(5))
print(power(5, 3))
def sums(*nums):
result = 0
for i in nums:
result += i
return result
print(sums(1, 2, 3, 4, 5))
def person(name, age, **others):
print("Name:", name, "Age:", age, "Others: ", others)
extra = {"city": "DaLian", "gender": "Male"}
# 获得的室extra的拷贝,修改不会影响extra的值
person("Yummy", 8, **extra)
def person_two(name, age, *, city):
print("Name:", name, "Age:", age, "City:", city)
person_two("Yummy", 8, city="DaLian")
def f1(a, b, c=1, *args, **kwargs):
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kwargs)
f1(1, 2, 4, 4, 4, 4, kwargs={"5": 5})
2021-11-16 - 无题
发表于
|
阅读次数
2021-11-14 - 累了
发表于
|
阅读次数
2020-01-10 - 周末了
发表于
|
阅读次数
20191231 - 新年快乐
发表于
|
阅读次数
20191206 - 下雪了 雪
发表于
|
阅读次数
今天是入冬以来第一次飘雪花。感觉长大以后看见雪的次数越来越少了,孩子一直问我什么时候下雪,可惜我不会下雪。
又是一个月过去了,不知不觉。工作很忙,每天都很忙碌。做了年终总结,听了同事的发言,敬佩不已。总结起来10个字,陈述起来近千言,以后得学习。
最近工作的插曲和波折有点多,吸取经验、教训吧。学到一个词:“知人知面不知心“
把办公桌、笔记和工作资料都重新做了整理,希望自己的思路更信息。
看了一段时间历史,大概弥补的断代的信息。
明年重点学习内容是弥补期货业务知识短板。
未来目标,希望能考个CFA。
时间很快,有些东西会遗忘,有些东西会铭记。
不管发生什么,切记坦然面对。
最后两个字:耐心。
20191106 - 冬天很暖 晴
发表于
|
阅读次数
今年是印象里最暖的一个冬天了。昨天家里已经供暖了,而在供暖之前也从未感觉到寒冷。毛衫、毛裤也没穿过,难道是全球变暖么?
最近工作确实很忙,有一个规划报告、一个研究报告、几个其他材料要写。一会这个急,一会那个紧,但我只能一个一个字的敲。
每隔几天还是想来做个总结,思考思考,回忆回忆。
为了孩子,我开始陪他一起跑步,所以我的膝盖有点疼。
最近孩子情绪起伏挺大的,有好有坏吧,但确实成长了,陪伴确实很重要,我很感激,我能陪着他长大。
身体很重要,多多保重。