python学习之路

Python 16

2018-01-12  本文已影响0人  Jack_Hsin
  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????????
上一篇 下一篇

猜你喜欢

热点阅读