美文网首页
python练习二(函数装饰器)

python练习二(函数装饰器)

作者: 幺姨母 | 来源:发表于2020-04-05 20:49 被阅读0次

第一部分:基础练习

1.1 请完成代码,实现输入任意多个空格分隔的浮点数,并打印输出这些浮点数的和

参考:
a, b = map(int, input('输入空格分隔的两个数:').split())
print(a+b)

提示:同时赋值两个变量的这个语法叫 Tuple Unpacking

#map和sum的用法: sum(list(map(float, inp.split())))

def do_sum(inp):
    # 补充完成函数 Write here
    return sum(list(map(float, inp.split())))

# 下面的语句用来检验 do_sum 的正确性
assert do_sum('1 2') == 3
assert do_sum('1 2 3 4.6 5 -1.1') == 14.5
assert do_sum('-123') == -123
print('Test passed!')
Test passed!

1.2 定义一个函数func(listinfo) listinfo:为列表,listinfo = [133, 88, 24, 33, 232, 44, 11, 44],剔除列表中大于100的奇数

#filter和lambda的用法: list(filter(lambda x: x <= 100 or x % 2 == 0, listinfo))

def func(listinfo):
    #TODO
    return list(filter(lambda x: x <= 100 or x % 2 == 0, listinfo))
print(func([133, 88, 24, 33, 232, 44, 11, 44]))
[88, 24, 33, 232, 44, 11, 44]

1.3 牛顿迭代法

以方程:x ^3-0.2x ^2-0.2x-1.2=0为例,编写程序求该方程的根,精度为0.00000001

#牛顿迭代法: temp = temp - tempval / getdao(a, temp)
#浮点数比较大小: math.isclose(tempval, 0.0)
#保留位数: print("%.8f" % getres([-1.2, -0.2, -0.2, 1]))

import math

#求函数值
def getval(a, x):
    r = 0.0
    b = reversed(a)
    for element in b:
        r = r * x + element
    return r
        
#求导
def getdao(a, x):
    b = []
    for i in range(1, len(a)):
        b.append(a[i] * i) 
    return getval(b, x)

#牛顿迭代
def getres(a):
    temp = 0.0;
    tempval = getval(a, temp)
    while not math.isclose(tempval, 0.0):
        temp = temp - tempval / getdao(a, temp)
        tempval = getval(a, temp)
    return temp

print("%.8f" % getres([-1.2, -0.2, -0.2, 1]))
    
    
1.20000000

1.4 设计一个decorator,它可作用于任何函数上,并打印该函数的执行时间

#时间长: time.process_time()
#函数装饰器

import time

def biubiu(func):
    def inner():
        print("------decorate-------")
        start = time.process_time()
        func()
        end = time.process_time()
        print(str(end - start) + " seconds are used.")
        return 
    return inner

@biubiu
def a():
    print("i am a")
    return

@biubiu
def b():
    print("i am b")
    return

a()
b()     
------decorate-------
i am a
4.7999999999603915e-05 seconds are used.
------decorate-------
i am b
4.6000000001100716e-05 seconds are used.

1.5 用匿名函数改造下面的代码

def is_odd(n):
    return n % 2 == 1

L = list(filter(is_odd, range(1, 20)))
print(L)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
#TODO

L = list(filter(lambda x: x % 2 == 1, range(1, 20)))

print(L)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

第二部分:进阶练习

2.1 给定一个数组nums找最长递增子序列长度(提示:用装饰器实现动态规划算法的记忆存储)

#动态规划和函数装饰器

def memorize(func):
    memory = {}
    def inner(a, i):
        if i not in memory:
            memory[i] = func(a, i)
        return memory[i]
    return inner

@memorize
def findres(a, i):
    if i == 0:
        return 1
    else:
        temp = 0
        for j in range(0, i):
            ttemp = findres(a, j)
            if a[i] > a[j] and ttemp > temp:
                temp = ttemp
    return temp + 1
        
def lis(nums):
    #TODO
    temp = 0
    for i in range(0, len(nums)):
        ttemp = findres(nums, i)
        if ttemp > temp:
            temp = ttemp
    return temp

print(lis([7,6,1,5,4,3,2,3,4,2,5]))

5

2.2 从开发的代码库中得到一组数据,表示每个文件的代码变更情况

{'login.py': 'a 8 d 2 u 3', 'order.py': 'a 15 d 0 u 34', 'info.py': 'a 1 d 20 u 5'}

其中 a表示新增行数,d表示删除行数,u表示修改行数。login.py的变更行数为13

要求:统计出每个文件的变更行数(提示:通过try方法)

s = {'login.py': 'a 8 d 2 u 3', 'order.py': 'a 15 d 0 u 34', 'info.py': 'a 1 d 20 u 5'}
res = {}
for k, v in s.items():
    try:
        v = v.split(" ")
        n = int(v[1]) + int(v[3]) + int(v[5])
        res[k] = n
    except:
        print("exception!")
print(res)
{'login.py': 13, 'order.py': 49, 'info.py': 26}

2.3 运行下面的代码,根据异常信息进行分析,定位出错误源头,并修复

#请看下一个代码块
#小数字符串转换成整数
#把int(s)改成了float(s)

from functools import reduce

def str2num(s):
    return int(s)

def calc(exp):
    ss = exp.split('+')
    ns = map(str2num, ss)
    return reduce(lambda acc, x: acc + x, ns)

def main():
    r = calc('100 + 200 + 345')
    print('100 + 200 + 345 =', r)
    r = calc('99 + 88 + 7.6')
    print('99 + 88 + 7.6 =', r)

main()
100 + 200 + 345 = 645



---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-41-ad8040b068b8> in <module>
     15     print('99 + 88 + 7.6 =', r)
     16 
---> 17 main()


<ipython-input-41-ad8040b068b8> in main()
     12     r = calc('100 + 200 + 345')
     13     print('100 + 200 + 345 =', r)
---> 14     r = calc('99 + 88 + 7.6')
     15     print('99 + 88 + 7.6 =', r)
     16 


<ipython-input-41-ad8040b068b8> in calc(exp)
      7     ss = exp.split('+')
      8     ns = map(str2num, ss)
----> 9     return reduce(lambda acc, x: acc + x, ns)
     10 
     11 def main():


<ipython-input-41-ad8040b068b8> in str2num(s)
      2 
      3 def str2num(s):
----> 4     return int(s)
      5 
      6 def calc(exp):


ValueError: invalid literal for int() with base 10: ' 7.6'
from functools import reduce

def str2num(s):
    return float(s)

def calc(exp):
    ss = exp.split('+')
    ns = map(str2num, ss)
    return reduce(lambda acc, x: acc + x, ns)

def main():
    r = calc('100 + 200 + 345')
    print('100 + 200 + 345 =', r)
    r = calc('99 + 88 + 7.6')
    print('99 + 88 + 7.6 =', r)

main()
100 + 200 + 345 = 645.0
99 + 88 + 7.6 = 194.6

相关文章

  • Python装饰器

    Python装饰器 一、函数装饰器 1.无参装饰器 示例:日志记录装饰器 2.带参装饰器 示例: 二、类装饰器 示例:

  • python装饰器

    装饰器简述 要理解装饰器需要知道Python高阶函数和python闭包,Python高阶函数可以接受函数作为参数,...

  • python 装饰器 补充

    重新理解python 装饰器 python 装饰器是一个函数,被装饰器所装饰的代码块最终也是一个函数这个对于一般的...

  • Flask 视图和路由的进阶技能

    视图装饰器 Python 装饰器是用于转换其它函数的函数。当一个装饰的函数被调用的时候,装饰器也会被调用。接着装饰...

  • 解析Python中的装饰器

    python中的函数也是对象,函数可以被当作变量传递。 装饰器在python中功能非常强大,装饰器允许对原有函数行...

  • day2-python3函数

    今天练习了python3的各类型函数。包括: 基本语法 高级函数 递归 生成器与迭代器 闭包与装饰器 练习题代码实...

  • 理解 Python 装饰器与回调函数

    1.理解 Python 装饰器2.Python装饰器和回调函数回调函数就是一个通过函数指针调用的函数。如果你把函数...

  • 函数装饰器(Function Decorators)

    函数装饰器(Function Decorators) python中函数装饰器的使用和Java中注解类似, 直接在...

  • 解惑,从新认识python装饰器

    概念 python有两种装饰器: 函数装饰器(function decorators) 类装饰器(class de...

  • 装饰器函数

    在Python有一类特殊的函数,叫装饰器函数。装饰器函数可以在函数的调用的时候,将装饰器的内容注入到函数之中。在定...

网友评论

      本文标题:python练习二(函数装饰器)

      本文链接:https://www.haomeiwen.com/subject/gudiphtx.html