zoukankan      html  css  js  c++  java
  • 建议51:函数式编程实战

    # -*-  coding:utf-8 -*-
    
    #不要在lists上迭代。使用map和reduce。
    
    #Map接受一个方法和一个集合作为参数。它创建一个新的空集合,以每一个集合中的元素作为参数调用这个传入的方法,
    #然后把返回值插入到新创建的集合中。最后返回那个新集合。
    
    name_lengths = map(len, ["Mary", "Isla", "Sam"])
     
    print name_lengths
    # => [4, 4, 3]
    
    #接下来这个map将传入的collection中每个元素都做平方操作:
    squares = map(lambda x: x * x, [0, 1, 2, 3, 4])
     
    print squares
    # => [0, 1, 4, 9, 16]
    
    #下面的非函数式代码接受一个真名列表,然后用随机指定的代号来替换真名。
    import random
     
    names = ['Mary', 'Isla', 'Sam']
    code_names = ['Mr. Pink', 'Mr. Orange', 'Mr. Blonde']
     
    for i in range(len(names)):
        names[i] = random.choice(code_names)
     
    print names
    # => ['Mr. Blonde', 'Mr. Blonde', 'Mr. Blonde']
    
    #用map重写:
    import random
     
    names = ['Mary', 'Isla', 'Sam']
     
    secret_names = map(lambda x: random.choice(['Mr. Pink',
                                                'Mr. Orange',
                                                'Mr. Blonde']),
                       names)
    
    #Reduce 接受一个方法和一个集合做参数。返回通过这个方法迭代容器中所有元素产生的结果。
    
    sum = reduce(lambda a, x: a + x, [0, 1, 2, 3, 4])
     
    print sum
    # => 10
    
    sentences = ['Mary read a story to Sam and Isla.',
                 'Isla cuddled Sam.',
                 'Sam chortled.']
     
    sam_count = 0
    for sentence in sentences:
        sam_count += sentence.count('Sam')
     
    print sam_count
    # => 3
    
    sentences = ['Mary read a story to Sam and Isla.',
                 'Isla cuddled Sam.',
                 'Sam chortled.']
     
    sam_count = reduce(lambda a, x: a + x.count('Sam'),
                       sentences,
                       0)
    
    #尝试用map,reduce和filter重写下面的代码。Filter接受一个方法和一个集合。返回集合中使方法返回true的元素。
    people = [{'name': 'Mary', 'height': 160},
              {'name': 'Isla', 'height': 80},
              {'name': 'Sam'}]
     
    heights = map(lambda x: x['height'],
                  filter(lambda x: 'height' in x, people))
     
    if len(heights) > 0:
        from operator import add
        average_height = reduce(add, heights) / len(heights)
    
    
    #移除状态
    from random import random
     
    def move_cars(car_positions):
        return map(lambda x: x + 1 if random() > 0.3 else x,
                   car_positions)
     
    def output_car(car_position):
        return '-' * car_position
     
    def run_step_of_race(state):
        return {'time': state['time'] - 1,
                'car_positions': move_cars(state['car_positions'])}
     
    def draw(state):
        print ''
        print 'n'.join(map(output_car, state['car_positions']))
     
    def race(state):
        draw(state)
        if state['time']:
            race(run_step_of_race(state))
     
    race({'time': 5,
          'car_positions': [1, 1, 1]})
  • 相关阅读:
    友元函数
    异常处理
    RTTI
    接口类
    纯虚函数和抽象类
    虚函数与虚析构函数原理
    查看表空间使用率及shrink 表空间
    RAC fail over 测试
    js判断数组中是不是有某个元素
    layui 表格图片放大
  • 原文地址:https://www.cnblogs.com/tychyg/p/4935977.html
Copyright © 2011-2022 走看看