Python 之 高阶函数实践

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_44641053/article/details/101158705

Python 之 高阶函数实践

Python 之 高阶函数实践练习

  1. (华为机试练习)

    题目描述:数据表记录包含表索引和数值,请对表索引相同的记录进行合并,即将相索引的数值进行求和运算,输出按照key值升序进行输出。

    • 输入描述:先输入键值对的个数,然后输入成对的index和value值,以空格隔开

    • 输出描述:输出合并后的键值对(多行)

    • 示例1:

        		输入
        		
        		 4
        		 0 1
        		 0 2
        		 1 2
        		 3 4
      
      
      
        		输出
        		
        		 0 3
        		 1 2
        		 3 4
      

    脚本:

    				d = dict()
    				Num = input("please input Num: ")
    				for i in range(Num):
    				    N = raw_input("please input index and value: ")
    				    if d.has_key(N.split()[0]):
    				        New = str(int(d[N.split()[0]]) + int(N.split()[1]))
    				        d.pop(N.split()[0])
    				        d.setdefault(N.split()[0], New)
    				    else:
    				        d.setdefault(N.split()[0], N.split()[1])
    				        
    				for j, k in sorted(d.items()):
    				    print(j, k)
    
    

  1. 题目描述

    现在 IPV4 下用一个32位无符号整数来表示,一般用点分方式来显示,点将IP地址分成4部分,每个部分为8位,表示成一个无符号整数(因此不需要用正号出现),10.137.17.1,是我们非常熟悉的IP地址,一个IP地址串中没有空格出现(因为要表示成一个32数字)。

    现在需要用程序来判断IP是否合法。

    输入描述:输入一个ip地址

    输出描述:返回判断的结果YES or NO

    示例1:

     		输入: 10.138.15.1 
     		
     		输出: YES
    

    脚本:

    				IP = raw_input("please input IP: ")
    				for i in IP:
    				    if not (i.isdigit() or i =="."):
    				        print("NO")
    				        exit(1)
    				else:
    				    if len(IP.split(".")) == 4:
    				        for j in range(4):
    				            if int(IP.split(".")[j])>=0 and int(IP.split(".")[j])<=255:
    				                print("YES")
    				                exit()
    				            else:
    				                print("NO")
    				                exit(1)
    				    else:
    				        print("NO")
    				        exit(1)
    

3.函数式编程考察

用 filter() 进行函数式编程,写一段代码来给出一个年份的列表并返回一个只有闰年的列表列表解析式实现方式呢?

				def fun(N):
				     if (N % 400 == 0) or (N % 4 == 0 and N % 100 != 0):
				         return True
				     else:
				         return False
				Year = raw_input("please input Year: ")
				li = []
				for i in Year:
				    if not (i.isdigit() or i.isspace()):
				        print("input Error!!!")
				        exit(1)
				for j in Year.split():
				    li.append(int(j))
				li = list(set(li))
				print(filter(fun, li))

4.携程旅行网

给定一个整型数组,将数组中所有的”0”移到末尾,非”0”项保持顺序不变在原始数组上进行操作,勿创建新的数组

输入

			第一行是数组长度
			后续每一行是数组的第一条记录

输出

			调整后的数组内容

样例输入

			 4
			 0
			 7
			 0
			 2

样例输出

			 7
			 2
			 0
			 0
				array = [1, 0, 4, 0, 3, 2, 0, 1]
				print(sorted(array, key=lambda x: 1 if x == 0 else 0))
				
				# 结果:
				[1, 4, 3, 2, 1, 0, 0, 0]

猜你喜欢

转载自blog.csdn.net/qq_44641053/article/details/101158705