python之高阶函数与匿名函数

1.随机生成验证码,快速生成内推码

   生成码由数字与字母组合

   import     random      

   import     string              导入字符串模块

   s=string.ascii_letters   +    string.digits     s为全部的大小写字母与1到10的整形数字

   print (s)              结果为:abc.....zABC......Z0123456789

   def  d(num):

         return    ''.join(random.sample(  s,num  ) )     每num位数用合并在一起

   print( [d(5)   for   i     in   range(100) ] )                 生成100个五位验证码,想生成几位,将5改为几。

   结果为:[ '25rtf'   ,  '24Rrt' , '5etyS',.............]

   小插曲

           ord('a')       输出为97           chr(97)   输出为  'a'      阿斯卡码值与字母的转换

2.凯撒加密与暴力破解

      

# 凯撒加密---加密算法
#       在密码学中,恺撒密码是一种最简单且最广为人知的加密技术。它是一种替换加密的技术,
#       明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文。
import string


# abcdefghijklmnopqrstuvwxyz      ABCDEFGHIJKLMNOPQRSTUVWXYZ
# defghijklmnopqrstuvwxyzabc      DEFGHIJKLMNOPQRSTUVWXYZABC


# 凯撒加密---加密算法的实现
def kaisacrypt(text='hello', k=3):
    # 对原有小写字母向右移动k位
    lower = string.ascii_lowercase[k:] + string.ascii_lowercase[:k]
    upper = string.ascii_uppercase[k:] + string.ascii_uppercase[:k]

    # 用于创建字符串映射的转换表'hello'
    table = str.maketrans(string.ascii_letters, lower+upper)
    # 根据转换表去转换对应的字符
    return text.translate(table)     

print(kaisa( ))         返回的是‘hello’经过转化后的‘khoor‘   

def check(text):
    """
    思路:
        测试文本中是否存在至少两个最常见的英文单词, 如果有, 则代表破解成功.
    """
    mostCommonWords = ('the', 'is', 'to', 'not', 'have', 'than', 'for', 'ok', 'and' )
    return  len([1 for word in mostCommonWords  if word in text])>2                 

# 暴力破解
def bruteForce(text):
    for i in range(26):
        # 1,2,3,4,5
        t = kaisacrypt(text, -i)
        if check(t):
            print(i)
            print(t)
            break

text = "If not to the sun for smiling, warm is still in the sun there, but wewill laugh more confident calm; if turned to found his own shadow, appropriate escape, the sun will be through the heart,warm each place behind the corner; if an outstretched palm cannot fall butterfly, then clenched waving arms, given power; if I can't have bright smile, it will face to the sunshine, and sunshine smile together, in full bloom."
cryptStr = kaisacrypt(text=text, k=18)
print(cryptStr)

bruteForce(cryptStr)

3.生产者消费者模型

import   random

import  time

def   consumer(name):

        print("%s准备买包子............"  %(name) )

        while   True:

              kind=yield

              print("%s购买%s包子成功..........."   %(name,kind)

c=consumer('海带')                                     

next(c)                                              会返回:海带准备买包子   

c.send("三鲜")                                 会返回:海带准备买包子    海带购买三鲜包子成功

def  producer(name):

       c1=consumer("用户1")

       c2=consumer("用户2")

       next(c1)                                      返回:用户1准备买包子

       next(c2)                                      返回:用户2准备买包子

       print("%s厨师正在生产包子.............")                                          粉条正在生产包子................

       kinds=['A',  'B',   'C',    'D' ]

       while True:

          #模拟生产数据耗费的时间

           time.sleep(random.random( ) )

           kind=random.choice(kinds)              kind在kinds里随机选取一个

           print("%s已经生产好%s包子了........''    %(name,kind) )        粉条已经生产好kind包子了

           c1.send(kind)                                                                              用户1购买kind包子成功

           c2.send(kind)                                                                              用户2购买kind包子成功

producer(''粉条")

整体显示:用户1准备买包子        用户2准备买包子    粉条厨师正在生产包子............ 粉条厨师已经生产好b包子了........    用户1购买

b包子成功     用户2购买b包子成功        粉条已经生产好c包子了        用户1购买c包子成功    用户2购买c包子成功      依次循环

4.python的高级特性

   列表,集合,字典生成式

  [ i **2   for i  in  range(1,3) ]                 [

  { i **2  for  i  in  range(1,3) ]

  { i  :  i**2 for    i  in  range(1,3) }          需要显示时打印出来即可

  创建生成器

  def   fun( ):

      while  True:

              print("welcome........")

              receive = yield     "hello"

              print(receive)

f=fun( )                     调用函数

print(f)                     显示是一个生成器,生成器创建成功

next(f)                      显示‘hello’       welcome.......    听到下一个yield前

f.send("维新“)         将‘维新‘送给yield

生成器的优势:可以节省空间

5.高阶函数

   函数本身可以赋值给变量

            print(pow(6,2) )

            f=pow

            print( f(6,2) )        返回值为6的平方是36

    传递的参数包含函数名

  def  fun(x,y,f):

           return  f(x,y)

  print( fun (3,4,pow) )       返回值是3的4次方为81

 map函数

 def    factoria(x):
    """对于x求阶乘"""
    res = 1
    for i in range(1, x + 1):
        res = res * i
    return res
 li = [random.randint(2, 7) for i in range(10)]     随机生成10个2到7的随机数
 print(list(map(factoria,      li)  ) )     

                       执行函数    执行的数字                         显示他们各自的阶乘结果

 reduce函数
 # reduce:
 #           - PYTHON2中, 为内置函数;
 #           - PYTHON3中, 导入reduce, from functools import  reduce

  3的阶乘
 def multi(x, y):
     return x * y
 print(reduce(multi, range(1, 4)))               结果为1*2*3=6

小插曲

要求用户输入三个数字,依次将接收的数转为整形,并赋值给a,b,c

6.sorted排序

  li=[ 2, 3, 4, 1,5]

  li.sort( )    默认是由小到大排序     返回值是[ 1,2,3,4,5 ]  

  如果要由大到小排序,须执行此命令

  li.sort (reverse=True)      

sortde排序与匿名函数

info = [
    # 商品名称  商品数量 商品价格
    ('apple3', 200, 32),
    ('apple4', 40, 12),
    ('apple1', 40, 2),
    ('apple2', 1000, 23),

  ]  默认是以第一个排序   apple1,apple2,apple3,apple4
# # 按照商品的数量进行排序, key代表排序的关键字
 print(sorted(info, key=lambda  x: x[1]))                  
# # 按照商品的价格进行排序, key代表排序的关键字
 print(sorted(info, key=lambda  x:x[2]))
 print(sorted(info, key=lambda  x: (x[1], -x[2])))        默认以第二个排序

字典里嵌套排序
d = {
    '003':{
        'name':'apple1',
        'count':100,
        'price':10
    },
    '002': {
        'name': 'apple1',
        'count': 200,
        'price': 2
    },
}
##x:  {'name': 'apple1', 'count': 100, 'price': 10}
print(sorted(d.values( ), key=lambda x: x['count']))         以value值里的count排序
print(sorted(d.values( ), key=lambda x: x['price']))          以value值里的price排序

7.内置高阶函数的max和min

 l = ['hello', 'a', 'hjded', 'dederfref']

 print(max(l, key=lambda  x: len(x)))                     返回 l 里最长的单词
 print(min(l, key=lambda  x: len(x)))                                     最短的单词

 d = {
    'user2':{1,2,4,6},
    'user3':{2,2,9,6},
    'user4':{3,2,5,6},}
 

 找出user3用户兴趣最相似的
  user1喜欢的电影
  film = {1,2,67}
 找出字典中跟user1最相似的(即跟user1喜欢的电影交集最多的)
 max films = max(d.values(), key=lambda  x: x & film )  
 print(maxfilms)    返回{1,2,4,6}

8.奇偶数排序

问题描述: 有一个整数列表(10个元素), 要求调整元素顺序,
          把所有的奇数放在前面, 偶数放在后面,

import random

li = [ random.randint(1, 10) for i in range(10) ]
print(li)            随机生成10个随机数

print(sorted(li, key=lambda x: 1 if x % 2 == 0 else 0))       奇数在前偶数在后排序

           

猜你喜欢

转载自blog.csdn.net/weixin_42719822/article/details/81805358