python练习二(函数装饰器)

2020-04-05  本文已影响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
上一篇 下一篇

猜你喜欢

热点阅读