13 练习题:匿名函数 内置函数Ⅱ 闭包

Posted raygor

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了13 练习题:匿名函数 内置函数Ⅱ 闭包相关的知识,希望对你有一定的参考价值。

# 1.看代码分析结果
# func_list = []
# for i in range(10):
#     func_list.append(lambda: i)
# v1 = func_list[0]()
# v2 = func_list[5]()
# print(v1, v2)

# result:
# 9 9



# 2.看代码分析结果
# func_list = []
# for i in range(10):
#     func_list.append(lambda x:x+i)
# v1 = func_list[0](2)
# v2 = func_list[5](1)
# print(v1,v2)

# result:
# 11 10



# 3.看代码分析结果
# func_list = []
# for i in range(10):
#     func_list.append(lambda x:x+i)
# for i in range(0,len(func_list)):
#     result = func_list[i](i)
#     print(result)

# result:
# 0 2 4 6 8 10 12 14 16 18



# 4.看代码写结果(面试题):
# def func(name):
#     v = lambda x:x+name
#     return v
#
# v1 = func(‘太白‘)  # closure: v1: v   name = ‘太白‘
# v2 = func(‘alex‘)  # closure: v2: v   name = ‘alex‘
# v3 = v1(‘银角‘)  # v(‘银角‘)
# v4 = v2(‘金角‘)  # v(‘金角‘)
# print(v1,v2,v3,v4)

# result:
# <function func.<locals>.<lambda> at 0x0000019B736BBD90> <function func.<locals>.<lambda> at 0x0000019B7387EEA0> 银角太白 金角alex



# 5.看代码写结果【面试题】
result = []
for i in range(10):
    func = lambda: i  # 注意:函数不执行,内部代码不会执行。
    result.append(func)
print(i)
print(result)
v1 = result[0]()
v2 = result[9]()
print(v1, v2)


# result:
# 9
# [<function <lambda> at 0x0000016314AB1F28>, <function <lambda> at 0x0000016314C8BD90>, <function <lambda> at 0x0000016314E4EEA0>, <function <lambda> at 0x0000016314E4F510>, <function <lambda> at 0x0000016314E4F598>, <function <lambda> at 0x0000016314E4F620>, <function <lambda> at 0x0000016314E4F6A8>, <function <lambda> at 0x0000016314E4F730>, <function <lambda> at 0x0000016314E4F7B8>, <function <lambda> at 0x0000016314E4F840>]
# 9 9



# 6.看代码分析结果【面试题】
def func(num):
    def inner():  # closure
        print(num)

    return inner


result = []
for i in range(10):
    f = func(i)
    result.append(f)
print(i)
print(result)
v1 = result[0]()
v2 = result[9]()
print(v1, v2)


# result:
# 9
# [<function func.<locals>.inner at 0x0000029DFF491F28>, <function func.<locals>.inner at 0x0000029DFF66BD90>, <function func.<locals>.inner at 0x0000029DFF82EEA0>, <function func.<locals>.inner at 0x0000029DFF82F510>, <function func.<locals>.inner at 0x0000029DFF82F598>, <function func.<locals>.inner at 0x0000029DFF82F620>, <function func.<locals>.inner at 0x0000029DFF82F6A8>, <function func.<locals>.inner at 0x0000029DFF82F730>, <function func.<locals>.inner at 0x0000029DFF82F7B8>, <function func.<locals>.inner at 0x0000029DFF82F840>]
# 0
# 9
# None None



# 7.看代码写结果【新浪微博面试题】
def func():
    for num in range(10):
        pass
    v4 = [lambda: num + 10, lambda: num + 100, lambda: num + 100, ]
    result1 = v4[1]()
    result2 = v4[2]()
    print(result1, result2)


func()


# result:
# 109 109



# 8.请编写一个函数实现将IP地址转换成一个整数。【面试题,较难,可以先做其他题】
# 如 10.3.9.12 转换规则为二进制:
#         10            00001010
#          3            00000011
#          9            00001001
#         12            00001100
# 再将以上二进制拼接起来计算十进制结果:00001010 00000011 00001001 00001100 = ?
def ip_to_decimal(ip_address):
    ip_sp_list = ip_address.split(‘.‘)
    ip_binary = ‘‘
    for i in ip_sp_list:
        ip_binary += bin(int(i))[2:].rjust(8, ‘0‘)
    # print(ip_binary)  # 00001010 00000011 00001001 00001100
    return int(ip_binary, 2)


print(ip_to_decimal(‘10.3.9.12‘))



# 9.都完成的做一下作业(下面题都是用内置函数或者和匿名函数结合做出):
# 9.1 用map来处理字符串列表,把列表中所有人都变成sb,比方alex_sb
# ? name=[‘oldboy’,‘alex‘,‘wusir‘]
name = [‘oldboy‘, ‘alex‘, ‘wusir‘]
name_sb = map(lambda str: str + ‘_sb‘, name)
print(list(name_sb))



# 9.2 用map来处理下述l,然后用list得到一个新的列表,列表中每个人的名字都是sb结尾
# l = [{‘name‘:‘alex‘},{‘name‘:‘y‘}]
# def func(dic):
#     dic[‘name‘] += ‘_sb‘
#     return dic
# l = [{‘name‘:‘alex‘},{‘name‘:‘y‘}]
# name_sb = map(func, l)
# print(list(name_sb))



# 9.3 用filter来处理,得到股票价格大于20的股票名字
#  shares={
# 	‘IBM‘:36.6,
# 	‘Lenovo‘:23.2,
# 	‘oldboy‘:21.2,
# 	‘ocean‘:10.2,
# }
# shares = {
#     ‘IBM‘: 36.6,
#     ‘Lenovo‘: 23.2,
#     ‘oldboy‘: 21.2,
#     ‘ocean‘: 10.2,
# }
# a = filter(lambda name: shares[name] > 20, shares)
# print(list(a))



# 9.4 有下面字典,得到购买每只股票的总价格,并放在一个迭代器中结果:list一下[9110.0, 27161.0,......]
# portfolio = [
#   {‘name‘: ‘IBM‘, ‘shares‘: 100, ‘price‘: 91.1},
# {‘name‘: ‘AAPL‘, ‘shares‘: 50, ‘price‘: 543.22},
# {‘name‘: ‘FB‘, ‘shares‘: 200, ‘price‘: 21.09},
# {‘name‘: ‘HPQ‘, ‘shares‘: 35, ‘price‘: 31.75},
# {‘name‘: ‘YHOO‘, ‘shares‘: 45, ‘price‘: 16.35},
# {‘name‘: ‘ACME‘, ‘shares‘: 75, ‘price‘: 115.65}]
portfolio = [
    {‘name‘: ‘IBM‘, ‘shares‘: 100, ‘price‘: 91.1},
    {‘name‘: ‘AAPL‘, ‘shares‘: 50, ‘price‘: 543.22},
    {‘name‘: ‘FB‘, ‘shares‘: 200, ‘price‘: 21.09},
    {‘name‘: ‘HPQ‘, ‘shares‘: 35, ‘price‘: 31.75},
    {‘name‘: ‘YHOO‘, ‘shares‘: 45, ‘price‘: 16.35},
    {‘name‘: ‘ACME‘, ‘shares‘: 75, ‘price‘: 115.65}]
# aggregate = map(lambda dic: round(dic[‘shares‘] * dic[‘price‘], 1), portfolio)
# print(list(aggregate))



# 9.5 还是上面的字典,用filter过滤出单价大于100的股票。
# price_over_100 = filter(lambda dic: dic[‘price‘] > 100, portfolio)
# print(list(price_over_100))



# 9.6 有下列三种数据类型,
# l1 = [1,2,3,4,5,6]
# l2 = [‘oldboy‘,‘alex‘,‘wusir‘,‘太白‘,‘日天‘]
# tu = (‘**‘,‘***‘,‘****‘,‘*******‘)
# 写代码,最终得到的是(每个元祖第一个元素>2,第三个*至少是4个。)
# [(3, ‘wusir‘, ‘****‘), (4, ‘太白‘, ‘*******‘)]这样的数据。
# l1 = [1,2,3,4,5,6]
# l2 = [‘oldboy‘,‘alex‘,‘wusir‘,‘太白‘,‘日天‘]
# tu = (‘**‘,‘***‘,‘****‘,‘*******‘)
# z1 = zip(l1,l2,tu)
# z1 = filter(lambda tu: tu[0] > 2, z1)
# print(list(z1))



# 9.7 有如下数据类型(实战题):
#  l1 = [ {‘sales_volumn‘: 0},
# 	{‘sales_volumn‘: 108},
# 	{‘sales_volumn‘: 337},
# 	{‘sales_volumn‘: 475},
# 	{‘sales_volumn‘: 396},
# 	{‘sales_volumn‘: 172},
# 	{‘sales_volumn‘: 9},
# 	{‘sales_volumn‘: 58},
# 	{‘sales_volumn‘: 272},
# 	{‘sales_volumn‘: 456},
# 	{‘sales_volumn‘: 440},
# 	{‘sales_volumn‘: 239}]
# ? 将l1按照列表中的每个字典的values大小进行排序,形成一个新的列表。
# l1 = [{‘sales_volumn‘: 0},
#       {‘sales_volumn‘: 108},
#       {‘sales_volumn‘: 337},
#       {‘sales_volumn‘: 475},
#       {‘sales_volumn‘: 396},
#       {‘sales_volumn‘: 172},
#       {‘sales_volumn‘: 9},
#       {‘sales_volumn‘: 58},
#       {‘sales_volumn‘: 272},
#       {‘sales_volumn‘: 456},
#       {‘sales_volumn‘: 440},
#       {‘sales_volumn‘: 239}]
# sorted_l1 = sorted(l1, key=lambda dic: dic[‘sales_volumn‘])
# print(sorted_l1)



# 10.求结果(面试题)
# v = [lambda :x for x in range(10)]
# print(v)
# print(v[0])
# print(v[0]())
# result:
# [<function <listcomp>.<lambda> at 0x0000018196A9FAE8>, <function <listcomp>.<lambda> at 0x0000018196A9FB70>, <function <listcomp>.<lambda> at 0x0000018196A9FBF8>, <function <listcomp>.<lambda> at 0x0000018196A9FC80>, <function <listcomp>.<lambda> at 0x0000018196A9FD08>, <function <listcomp>.<lambda> at 0x0000018196A9FD90>, <function <listcomp>.<lambda> at 0x0000018196A9FE18>, <function <listcomp>.<lambda> at 0x0000018196A9FEA0>, <function <listcomp>.<lambda> at 0x0000018196A9FF28>, <function <listcomp>.<lambda> at 0x0000018196AA5048>]
# <function <listcomp>.<lambda> at 0x0000018196A9FAE8>
# 9



# 11.求结果(面试题)
# v = (lambda :x for x in range(10))
# print(v) # 生成器
# # print(v[0])  # 生成器不可用索引方式读取
# # print(v[0]())  # 生成器不可用索引方式读取
# print(next(v))  # 函数
# print(next(v)())  # 1



# 12.map(str,[1,2,3,4,5,6,7,8,9])输出是什么? (面试题)
# 一个迭代器,转换为list内容为[‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘]



# 13.求结果:(面试题,比较难,先做其他题)
# def num():
# 	return [lambda x:i*x for i in range(4)]
# print([m(2) for m in num()])
# [6, 6, 6, 6]



# 14.有一个数组[3,4,1,2,5,6,6,5,4,3,3]请写一个函数,找出该数组中没有重复的数
# 的总和(上面数据的么有重复的总和为1+2=3)(面试题)
def no_repeat_sum(array):
    obj = filter(lambda x: array.count(x) == 1, array)
    return sum(obj)
print(no_repeat_sum([3,4,1,2,5,6,6,5,4,3,3]))



# 15.写一个函数完成三次登陆功能:
# 用户的用户名密码从一个文件register中取出。
# register文件包含多个用户名,密码,用户名密码通过|隔开,每个人的用户名密码占用文件中一行。
# 完成三次验证,三次验证不成功则登录失败,登录失败返回False。
# 登陆成功返回True。
def get_userinfo():
    users_dic = {}
    with open(r‘04 作业
egister‘, encoding=‘utf-8‘, mode=‘r‘) as file_handler:
        for line in file_handler:
            temp_list = line.split(‘|‘)
            users_dic.setdefault(temp_list[0].strip(), temp_list[1].strip())
    return users_dic
def login():
    for i in range(3):
        users_dic = get_userinfo()
        user = input(‘USER:
‘)
        password = input(‘PASSWORD:
‘)
        if user in users_dic and password == users_dic[user]:
            print(‘u success!‘)
            return True
    return False
# login()



# 16.再写一个函数完成注册功能:
# 用户输入用户名密码注册。
# 注册时要验证(文件regsiter中)用户名是否存在,如果存在则让其重新输入用户名,如果不存在,则注册成功。
# 注册成功后,将注册成功的用户名,密码写入regsiter文件,并以 | 隔开。
# 注册成功后,返回True,否则返回False。
def get_userinfo():
    users_dic = {}
    with open(r‘04 作业
egister‘, encoding=‘utf-8‘, mode=‘r‘) as file_handler:
        for line in file_handler:
            temp_list = line.split(‘|‘)
            users_dic.setdefault(temp_list[0].strip(), temp_list[1].strip())
    return users_dic

def new_user(new_user_list):
    users_dic = get_userinfo()
    if new_user_list[0] in users_dic:
        return False
    with open(r‘04 作业
egister‘, encoding=‘utf-8‘, mode=‘a‘) as file_handler:
        file_handler.write(‘
‘ + new_user_list[0] + ‘|‘ + new_user_list[1])
    return True

def create_account():
    for i in range(3):
        new_user_list =[]
        user = input(‘USER:
‘)
        password = input(‘PASSWORD:
‘)
        new_user_list.append(user)
        new_user_list.append(password)
        if new_user(new_user_list):
            print(‘U create a new account!‘)
            return True
    return False



# 17.完成一个员工信息表的增删功能(选做题,有时间做,没时间周末做)。
# 文件存储格式如下:
# id,name,age,phone,job
# 1,Alex,22,13651054608,IT
# 2,太白,23,13304320533,Tearcher
# 3,nezha,25,1333235322,IT
# 现在要让你实现两个功能:
# 第一个功能是实现给文件增加数据,用户通过输入姓名,年龄,电话,工作,
# 给原文件增加数据(增加的数据默认追加到原数据最后一行的下一行),但id要实现自增(id自增有些难度,id是不需要用户输入的但是必须按照顺序增加)。
# 第二个功能是实现给原文件删除数据,用户只需输入id,则将原文件对应的这一条数据删除
# (删除后下面的id不变,比如此时你输入1,则将第一条数据删除,但是下面所有数据的id值不变及太白,nezha的 id不变)。
def del_employee(id):
    flag = 0
    import os
    with open(r‘04 作业employees‘, encoding=‘utf-8‘, mode=‘r‘) as file_handler_1,            open(r‘04 作业employees.bak‘, encoding=‘utf-8‘, mode=‘w‘) as file_handler_2:
        for line in file_handler_1:
            temp_line = line
            temp_line.split(‘,‘)
            if temp_line[0] != id:
                flag = 1
                file_handler_2.write(line)
    os.remove(r‘04 作业employees‘)
    os.rename(r‘04 作业employees.bak‘, r‘04 作业employees‘)
    if flag == 1:
        return True
    print(‘No Found!‘)
    return False

def add_employee(employee):
    with open(r‘04 作业employees‘, encoding=‘utf-8‘, mode=‘r+‘) as file_handler:
        for line in file_handler:
            pass
        line.split(‘,‘)
        id = int(line[0]) + 1
        file_handler.write(‘
‘ + str(id))
        for item in employee:
            file_handler.write(‘,‘ + employee[item])

def employee_management():
    for i in range(3):
        mode = input(‘select ur mode!
input 1 to add a new employee
input 2 to del an employee
‘)
        if mode == ‘1‘:
            employee = {}
            employee.setdefault(‘name‘, input(‘name?
‘))
            employee.setdefault(‘age‘, input(‘age?
‘))
            employee.setdefault(‘phone‘, input(‘phone?
‘))
            employee.setdefault(‘job‘, input(‘job?
‘))
            add_employee(employee)
            return True
        elif mode == ‘2‘:
            id = input(‘del id?
‘)
            if del_employee(id):
                print(‘Del succeed.
‘)
            else:
                print(‘Del failed.
‘)
                return True
        else:
            print(‘PLS INPUT CORRECT MODE NUM.
‘)
        return False
employee_management()

以上是关于13 练习题:匿名函数 内置函数Ⅱ 闭包的主要内容,如果未能解决你的问题,请参考以下文章

python之路--day13---函数--三元表达式,递归,匿名函数,内置函数-----练习

内置函数补充匿名函数及闭包

学习13.内容# 1.内置函数二 # 2.闭包

内置函数,匿名函数与闭包

Python之路day13-内置函数_lambda_闭包

Python-内置函数1匿名函数闭包