Python 16

  1. 课上代码
>>> count = 5
>>> def MyFun():
    count = 10
    print(10)

    
>>> MyFun()
10
>>> print(count)
5
>>> def MyFun():
    global count
    count = 10
    print(10)

    
>>> MyFun()
10
>>> print(count)
10
>>> def fun1():
    print('fun1()正在被调用...')
    def fun2():
        print('fun2()正在被调用...')
    fun2()

    
>>> fun1()
fun1()正在被调用...
fun2()正在被调用...
>>> def FunX(x):
    def FunY(y):
        return x * y
    return FunY

>>> i = FunX(8)
>>> i
<function FunX.<locals>.FunY at 0x0000017712511620>
>>> type(i)
<class 'function'>
>>> i(5)
40
>>> FunX(8)(5)
40
>>> FunY(5)
Traceback (most recent call last):
  File "<pyshell#33>", line 1, in <module>
    FunY(5)
NameError: name 'FunY' is not defined
>>> def Fun1():
    x = 5
    def Fun2():
        x *= x
        return x
    return Fun2()

>>> Fun1()
Traceback (most recent call last):
  File "<pyshell#41>", line 1, in <module>
    Fun1()
  File "<pyshell#40>", line 6, in Fun1
    return Fun2()
  File "<pyshell#40>", line 4, in Fun2
    x *= x
UnboundLocalError: local variable 'x' referenced before assignment
>>> Fun2()
Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    Fun2()
NameError: name 'Fun2' is not defined

#修改方法
>>> def Fun1():
    x = [5]
    def Fun2():
        x[0] *= x[0]
        return x
    return Fun2()

>>> Fun1()
[25]
>>> def Fun1():
    x = 5
    def Fun2():
        nonlocal x     #强制声明为不是一个局部变量
        x *= x
        return x
    return Fun2()

>>> Fun1()
25
>>> def ds(x):
    return 2 * x + 1

>>> ds(5)
11

'''python写一些执行脚本时,
使用lambda就可以省下定义函数过程,
比如说我们只是需要写个简单的脚本来管理服务器时间,
我们就不需要专门定义一个函数然后再写调用,
使用lambda就可以使得代码更加精简'''
'''对于一些比较抽象并且整个程序执行下来只需要调用一两次的函数,
有时候给函数起个名字也是比较头疼的问题,
使用lambda就不需要考虑命名的问题了'''
'''简化代码的可读性,
由于普通的函数阅读经常要跳到开头def定义部分,
使用lambda函数可以省去这样的步骤'''
>>> lambda x : 2 * x + 1
<function <lambda> at 0x101f62e18>
>>> g = lambda x : 2 * x + 1
>>> g(5)
11
>>> def add(x, y):
    return x + y

>>> add(3, 4)
7
>>> lambda x, y : x + y
<function <lambda> at 0x1120d27b8>
>>> g = lambda x, y : x + y
>>> g(3, 4)
7
>>> help(filter)
Help on class filter in module builtins:

class filter(object)
 |  filter(function or None, iterable) --> filter object
 |  
 |  Return an iterator yielding those items of iterable for which function(item)
 |  is true. If function is None, return the items that are true.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.

>>> filter(None, [1, 0, False, True])
<filter object at 0x1120c8ef0>
#filter()是过滤的bif

>>> list(filter(None, [1, 0, False, True]))
[1, True]
>>> def odd(x):
    return x % 2
#这个返回奇数的方式很巧妙

>>> temp = range(10)
>>> show = filter(odd, temp)
>>> list(show)
[1, 3, 5, 7, 9]
>>> list(filter(lambda x : x % 2, range(10)))
[1, 3, 5, 7, 9]
>>> list(map(lambda x : x * 2, range(10)))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
#map()是映射的bif

二. 测试题

  1. 请问如何访问funIn()呢?
>>> def funOut():
    def funIn():
        print("Bingo! You got me!")
    return funIn()
>>> funOut()
Bingo! You got me!
  1. 请问如何访问funIn()呢?
>>> def funOut():
    def funIn():
        print("Bingo! You got me!")
    return funIn
>>> funOut()()
Bingo! You got me!
#或者可以用
>>> go = funOut()
>>> go()
Bingo! You got me!
  1. 以下是闭包的一个例子,目测会打印什么内容?
def funX():
    x = 5
    def funY():
        nonlocal x
        x += 1
        return x
    return funY

a = funX()
print(a())
print(a())
print(a())
>>> 
=================== RESTART: C:\Users\xin\Desktop\game.py ===================
6
7
8
  1. 请将下面的匿名函数转变为普通的函数
>>> lambda x: x if x % 2 else None
>>> def function(x):
    if x % 2 == 1:
        return x
    else:
        return None
  1. 利用filter()和lambda表达式快速求出100以内所有3的倍数
>>> list(filter(lambda n: not(n % 3), range(1, 100)))
[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99]
  1. zip()会将两数以元组的形式绑定在一起,例如:
>>> list(zip([1, 3, 5, 7, 9], [2, 4, 6, 8, 10]))
[(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]

如果希望打包的形式是灵活多变的列表而不是元组,用map()和lambda表达式来解决

>>> list(map(lambda x, y: [x, y], [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]))
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
#直接把数据怼上去就行了
>>> def even(x):
    return x % 2 == 0

>>> def odd(x):
    return x % 2
>>> temp = range(1, 11)
>>> list(temp)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> show_odd = filter(odd, temp)
>>> show_even = filter(even, temp)
>>> list(show_odd)
[1, 3, 5, 7, 9]
>>> list(show_even)
[2, 4, 6, 8, 10]
>>> map(lambda x, y: [x, y], show_odd, show_even)
<map object at 0x112117198>
>>> list(map(lambda x, y: [x, y], show_odd, show_even))
[]
#这样求出的两个数组然后怼上去反而不行,暂不知原因,待详查
  1. 目测一下表达式会打印什么?
>>> def make_repeat(n):
    return lambda s: s * n

>>> double = make_repeat(2)
>>> print(double(8))
>>> print(double('FishC'))

#16
#FishCFishC

三. 动动手

  1. 统计长字符串中各个字符出现的次数
total_library = open('E:\\string1.txt', 'r')
total_library = total_library.read()
character_library = []
#check_character_number = 0
#L = []
for each in total_library:
    if each not in character_library:
        if each == '\n':
            print('\\n', total_library.count(each))
        else:
            print(each, total_library.count(each))
        character_library.append(each)
        
print(character_library)
        
        
'''length = len(character_library)
while length >= 1:
    check_character = character_library[length - 1]
    length = length - 1
    
    for i in total_library:
        if i == check_character:
            check_character_number += 1
    return check_character_number
    
print(check_character_number)
    L.append(check_character_number)

L.reverse()
print(L)    
print(character_library)'''
#注释处是我写的代码,目前还在debug
  1. 找出字符串中的密码,密码的埋藏点符合以下规律:
    (1) 每位密码为单个小写字母
    (2) 每位密码的左右两边均有且只有三个大写字母
#个人代码
total_library = open('E:\\string2.txt', 'r')
total_library = total_library.read()
length = len(total_library)
L = []

for i in range(3, length - 2):
    if 97 <= ord(total_library[i]) <= 122 and 65 <= ord(total_library[i + 1]) <= 90 and 65 <= ord(total_library[i - 1]) <= 90 and 65 <= ord(total_library[i + 2]) <= 90 and 65 <= ord(total_library[i - 2]) <= 90 and 65 <= ord(total_library[i + 3]) <= 90 and 65 <= ord(total_library[i - 3]) <= 90 and (ord(total_library[i + 4]) > 90 or ord(total_library[i + 4]) < 65) and (ord(total_library[i - 4]) > 90 or ord(total_library[i - 4]) < 65):   #(97 <= ord(total_library[i + 4]) <= 122 or 97 <= ord(total_library[i - 4]) <= 122 or 48 <= ord(total_library[i + 4]) <= 57 or 48 <= ord(total_library[i - 4]) <= 57):
        L.append(total_library[i])

print(L)
参考代码
str1 = open('E:\\string2.txt', 'r')
str1 = str1.read()

countA = 0   #统计前边的大写字母
countB = 0   #统计小写字母
countC = 0   #统计后边的大写字母
length = len(str1)

for i in range(length):
    if str1[i] == '\n':
        continue
        
    if str1[i].isupper():   #如果str1[i]是大写字母
        if countB:          #统计后边的大写字母
            countC += 1     
        else:               #如果未出现小写字母
            countC = 0      #清空后边大写字母的统计
            countA += 1     #统计前边的大写字母
                
    if str1[i].islower():   #如果str1[i]是小写字母
        if countA != 3:     #如果小写字母前边不是三个大写字母(不符合条件)
            countA = 0
            countB = 0
            countC = 0      #清空所有记录,重新统计
        else:               #如果小写字母前边是三个大写字母(符合条件)
            if countB:      #如果已经存在小写字母
                countA = 0  
                countB = 0
                countC = 0  #清空所有记录,重新统计(出现两个小写字母)
            else:           #如果该小写字母是唯一的
                countB = 1  
                countC = 0
                target = i  #countB记录出现小写字母,准备开始统计countC
                
    if countA == 3 and countC == 3:                     #如果前边和后边都是三个大写字母
        if i + 1 != length and str1[i + 1].isupper():   #如果后边第四个字母也是大写字母(不符合条件)
            countB = 0
            countC = 0                                  #清空B和C,重新统计
        else:                                           #如果后边仅有三个大写字母(符合所有条件)
            print(str1[target], end = '')
            countA = 3
            countB = 0 
            countC = 0                                  #打印结果,并清空所有记录,进入下一轮统计
#what the f**k????????
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,539评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,594评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,871评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,963评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,984评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,763评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,468评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,850评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,002评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,144评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,823评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,483评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,026评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,150评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,415评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,092评论 2 355

推荐阅读更多精彩内容