博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
9.Python——高阶函数+重点练习题
阅读量:2120 次
发布时间:2019-04-30

本文共 4686 字,大约阅读时间需要 15 分钟。

1.练习

练习1. 题目描述:

给定一个正整数,编写程序计算有多少对质数的和等于输入的这个正整数,>并输出结果。输入值小于1000。
如,输入为10, 程序应该输出结果为2。(共有两对质数的和为10,分别为(5,5),(3,7))

代码:

num = int(input())def isPrime(num):    for i in range(2,num):        if num % i == 0:            return False    else:        return Trueprimeli = [i for i in range(2,num) if isPrime(i)]print(primeli)primecount = 0# [2,3,5,7]for item in primeli:    if (num - item) in primeli and item <= num - item:      #只在num的一半进行数据运算        primecount += 1print(primecount)

思路:要想查询整数的质数库,先要产生一个质数库,isprime()快速生成

关键点:生成质数和,转化一下求和的过程

练习2.

1.需求1:假设有20个学生,学生名为westosX,学生分数在60~100之间,筛选出
2.成绩在90分以上得学生

代码:

import randomstuInfo = {
}for i in range(20): name = 'westos' + str(i) score = random.randint(60,100) stuInfo[name] = scoreprint(stuInfo)highscore = {
}for name,score in stuInfo.items(): if score > 90: highscore[name] = scoreprint(highscore)

进阶版:代码

print({
name: score for name,score in stuInfo.items() if score > 90})

解析:重点

{}:表示打印的格式
name:score表示键和值
for name,score in stuInfo.items()表示键和值的for循环
if score > 90 :嵌套在for循环内

练习3.

#2.key --> upperd = dict(a=1,b=2)print({
k.upper():v for k,v in d.items()})

练习4.

# 需求3:大小写key值合并,统一以小写输出d = dict(a=2, b=1, c=2, B=9, A=10)print({
k.lower():d.get(k.lower(),0) + d.get(k.upper(),0) for k in d})

出现错误:

{
: 12,
: 10,
: 10,
: 12,
: 2}

原因:

k.lower()处的()问题

2.高阶函数

返回函数的函数

1.求绝对值

f = absprint(f(-10))

结果:

10

举例:

def fun(x,y,f):    return f(x),f(y)print(fun(-10,34,abs))

结果:

10,34

3.内置高阶函数

  1. map()函数接收两个参数,一个是函数,一个是序列
    map将传入的函数依次作用到序列的每个元素,并且把结果
    作为新的序列返回
    代码:
print(list(map(abs,[-1,3,-5,-4])))

打印10个2到7的数字积

import randomdef f(x):    res = 1    for i in range(1,x+1):        res *= i    return resli = [random.randint(2,7) for i in range(10)]print(li)print(list(map(f,li)))
  1. reduce:把一个函数作用在一个序列上,这个函数必须接收两个
    参数,reduce把结果继续和序列的下一个元素做累积计算
    reduce(f,[x1,x2,x3,x4,x5]) = f(f(f(x1,x2),x3),x4)
python2:reduce是内置函数python3:from functools import reduce
from functools import reducedef add(x,y):    return x+yprint(reduce(add,[1,2,3,4,5]))

3.filter过滤函数

和map()类似,也接收一个函数和一个序列
但是和map()不同的是,filter()把传入的函数依次作用于
每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素

练习:过滤1到100所有的质数

#1~100 primedef isodd(num):    if num % 2 == 1:        return True    else:        return Falseprint(list(filter(isodd,range(100))))

4.逆序排序

li = [2,1,3,4]li.sort(reverse=True)print(li)print(sorted(li,reverse=True))
info = [    # 商品名称 商品数量 商品价格    ('apple1',200,32),    ('apple2',40,12),    ('apple3',40,2),    ('apple4',1000,23),    ('apple5',40,5)]#print(sorted(info))def sorted_by_count(x):    return x[1]def sorted_by_price(x):    return x[2]def sorted_by_count_price(x):    return x[1],x[2]print(sorted(info,key=sorted_by_count))print(sorted(info,key=sorted_by_price))print(sorted(info,key=sorted_by_count_price))
[('apple1', 200, 32), ('apple2', 40, 12), ('apple3', 40, 2), ('apple4', 1000, 23), ('apple5', 40, 5)][('apple2', 40, 12), ('apple3', 40, 2), ('apple5', 40, 5), ('apple1', 200, 32), ('apple4', 1000, 23)][('apple3', 40, 2), ('apple5', 40, 5), ('apple2', 40, 12), ('apple4', 1000, 23), ('apple1', 200, 32)][('apple3', 40, 2), ('apple5', 40, 5), ('apple2', 40, 12), ('apple1', 200, 32), ('apple4', 1000, 23)]
  1. 匿名函数的关键字为lambda 冒号前面是形参 冒号后面是返回值
print(reduce(lambda x,y:x+y,[1,2,3,4]))print(list(map(lambda x:x**2,range(5))))print(list(filter(lambda x:x%2==0,range(100))))print(sorted(nums,key=lambda x:1 if x == 0 else 0))

4.重点练习

(2018-携程-春招题)题目需求:

给定一个整形数组, 将数组中所有的0移动到末尾, 非0项保持不变;
在原始数组上进行移动操作, 勿创建新的数组;
输入:
第一行是数组长度, 后续每一行是数组的一条记录;
4
0
7
0
2
输出:
调整后数组的内容;
4
7
2
0
0
代码:

n = ''.join(input().split())li = [int(i) for i in n]def move_zero(item):    if item == 0:        return 2    else:        return 1print(sorted(li,key=move_zero))

思路:输入40702

4>1,0>2,…生成【12121】排序【11122】结果【47200】
return返回的2并非正式的数据,只是一种标志,与return x有本质的区别,并非只可以是1,2,如何的数据都可以
代码:

n=' '.join(input().split())l=[int(i) for i in n]def move(x):    if x==0:        return 1    else:        return 0print(sorted(l,key=move))

5.如何快速生成验证码,内推码

代码:

import randomimport string       #随机字母code_str = string.ascii_letters + string.digits# print(code_str)def gen_code(len=4):    # code = ''    # for i in range(len):    #     new_s = random.choice(code_str)    #     code += new_s    # print(code)    return ''.join(random.sample(code_str,len))# a = gen_code()# print(a)print([gen_code(len=6) for i in range(100)])print(random.sample(code_str,2))

解析:

random.sample(code_str,len) 随机选择len个数据

代码:

import randomimport stringcode_str=string.ascii_letters+string.digits# print(code_str)def fun(len=4):    return ''.join(random.sample(code_str,len))print(fun())print([fun() for i in range(100)])print(random.sample(code_str,5))

转载地址:http://edzrf.baihongyu.com/

你可能感兴趣的文章
Leetcode C++《热题 Hot 100-17》461.汉明距离
查看>>
Leetcode C++《热题 Hot 100-18》538.把二叉搜索树转换为累加树
查看>>
Leetcode C++《热题 Hot 100-19》543.二叉树的直径
查看>>
Leetcode C++《热题 Hot 100-21》581.最短无序连续子数组
查看>>
Leetcode C++《热题 Hot 100-22》2.两数相加
查看>>
Leetcode C++《热题 Hot 100-23》3.无重复字符的最长子串
查看>>
Leetcode C++《热题 Hot 100-24》5.最长回文子串
查看>>
Leetcode C++《热题 Hot 100-26》15.三数之和
查看>>
Leetcode C++《热题 Hot 100-27》17.电话号码的字母组合
查看>>
Leetcode C++《热题 Hot 100-28》19.删除链表的倒数第N个节点
查看>>
Leetcode C++《热题 Hot 100-29》22.括号生成
查看>>
Leetcode C++《热题 Hot 100-40》64.最小路径和
查看>>
Leetcode C++《热题 Hot 100-41》75.颜色分类
查看>>
Leetcode C++《热题 Hot 100-42》78.子集
查看>>
Leetcode C++《热题 Hot 100-43》94.二叉树的中序遍历
查看>>
Leetcode C++ 《第175场周赛-1 》5332.检查整数及其两倍数是否存在
查看>>
Leetcode C++ 《第175场周赛-2 》5333.制造字母异位词的最小步骤数
查看>>
Leetcode C++ 《第175场周赛-3》1348. 推文计数
查看>>
Leetcode C++《热题 Hot 100-44》102.二叉树的层次遍历
查看>>
Leetcode C++《热题 Hot 100-45》338.比特位计数
查看>>