首页 > 编程语言 > 详细

Python函数式编程:从入门到走火入魔

时间:2016-12-29 23:10:16      阅读:172      评论:0      收藏:0      [点我收藏+]

一行代码显示“爱心”

>>> print\n.join([‘‘.join([(AndyLove[(x-y)%8]if((x*0.05)**2+(y*0.1)**2-1)**3-(x*0.05)**2*(y*0.1)**3<=0 else )for x in range(-30,30)])for y in range(15,-15,-1)])

Python函数式编程:从入门到走火入魔

# @file: data.py
import random  
from collections import namedtuple

Student = namedtuple(Student, [id, ans])

N_Questions = 25  
N_Students = 20

def gen_random_list(opts, n):  
    return [random.choice(opts) for i in range(n)]

# 问题答案 ABCD 随机
ANS   = gen_random_list(ABCD, N_Questions)  
# 题目分值 1~5 分
SCORE = gen_random_list(range(1,6), N_Questions)

QUIZE = zip(ANS, SCORE)  
students = [  
    # 学生答案为 ABCD* 随机,* 代表未作答
    Student(_id, gen_random_list(ABCD*, N_Questions))
    for _id in range(1, N_Students+1)
]

print(QUIZE)  
# [(A, 3), (B, 1), (D, 1), ...
print(students)  
# [Student(id=1, ans=[C, B, A, ...

正常方法:

mport data  
def normal(students, quize):  
    for student in students:
        sid = student.id
        score = 0
        for i in range(len(quize)):
            if quize[i][0] == student.ans[i]:
                score += quize[i][1]
        print(sid, \t, score)
 
print(ID\tScore\n==================)  
normal(data.students, data.quize)  
"""
ID    Score  
==================
1      5  
2      12  
...
"""

函数式

def cal(quize):  
    def inner(student):
        filtered = filter(lambda x: x[0] == x[1][0], zip(student.ans, quize))
        reduced = reduce(lambda x, y: x + y[1][1], filtered, 0)
        print(student.id, \t, reduced)
    return inner
map(cal(QUIZE), students)  

 

 

其他好玩的东东

Python函数式编程:从入门到走火入魔

原文:http://www.cnblogs.com/jkmiao/p/6234882.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!