一行代码显示“爱心”
>>> print'\n'.join([''.join([('AndyLove'[(x-y)%]if((x*0.05)**+(y*0.1)**-)**-(x*0.05)***(y*0.1)**<= else' ')for x in range(-,)])for y in range(,-,-)])
Python函数式编程:从入门到走火入魔
# @file: data.py
import random
from collections import namedtuple Student = namedtuple('Student', ['id', 'ans']) N_Questions =
N_Students = def gen_random_list(opts, n):
return [random.choice(opts) for i in range(n)] # 问题答案 'ABCD' 随机
ANS = gen_random_list('ABCD', N_Questions)
# 题目分值 ~ 分
SCORE = gen_random_list(range(,), N_Questions) QUIZE = zip(ANS, SCORE)
students = [
# 学生答案为 'ABCD*' 随机,'*' 代表未作答
Student(_id, gen_random_list('ABCD*', N_Questions))
for _id in range(, N_Students+)
] print(QUIZE)
# [('A', ), ('B', ), ('D', ), ...
print(students)
# [Student(id=, ans=['C', 'B', 'A', ...
正常方法:
mport data
def normal(students, quize):
for student in students:
sid = student.id
score =
for i in range(len(quize)):
if quize[i][] == student.ans[i]:
score += quize[i][]
print(sid, '\t', score) print('ID\tScore\n==================')
normal(data.students, data.quize)
"""
ID Score
================== ...
"""
函数式
def cal(quize):
def inner(student):
filtered = filter(lambda x: x[] == x[][], zip(student.ans, quize))
reduced = reduce(lambda x, y: x + y[][], filtered, )
print(student.id, '\t', reduced)
return inner
map(cal(QUIZE), students)