Python_练习

第一题:

1. 创建add_log装饰器,被装饰的函数日志信息被记录到/var/log/python.log文件中;

2. 日志格式为: [字符串时间] Level: 日志级别 Name: 函数名称, Runtime:xxx  Result:xx

import time
import functools

# 需求: 编写一装饰器timeit, 用来装饰某函数执行时间的装饰器;
def timeit(fun):  # fun = world
    # 2. 注意: functools.wraps(fun): 可以保留add, world等函数的函数名, 帮助文档等属性信息;
    @functools.wraps(fun)
    def wrapper(*args, **kwargs):    # kwargs = {'a':1, 'b':2}
        """
        this is wrapper function。。。。
        :param args:
        :param kwargs:
        :return:
        """
        start_time = time.time()
        temp = fun(*args, **kwargs)         # world(a=1, b=2)
        end_time = time.time()
        print("[%s],函数名称为:%s,函数运行时间为%s 返回值为:%s" % (time.ctime(),fun.__name__, end_time - start_time,temp))
        return temp

    return wrapper

@timeit         # world = timeit(world)   # world =  wrapper
def world(**kwargs):
    """this is **kwargs test"""
    return kwargs


print(world(a=1, b=2))

第二题:

这个文本文件核心有几种情况:
序号 ID 操作者 操作行为 操作行为 操作对象
6883 556773833 RemyMCMXI
6880 556772838 Mindmatrix restored undeleted RemyMCMXI
6882 556771715 RemyMCMXI
6881 556770863 RemyMCMXI
6880 556673938 Liua97
6879 554350969 Epicgenius
6880 554332653 Alex

找到restored所在行,得到该行序号6880,然后往下读,找到第一个与其序号相同的行(liua97那行),然后记录下这两行之间所有的id值(包括restored那行),这个例子就是记录下556772838 556771715 556770863这三个id。

with open('/tmp/passwd') as reader:
    flag = False
    flag_number = None

    for line in reader:
        number, ID, *items = line.split()

        if not flag and 'restored' in items:
            flag = True
            flag_number = number
        elif flag and number == flag_number:
            flag = False
            flag_number = None

        if flag:
            print(ID)

第三题:

打印斐波那契数列列前十十列列,示例例如下(语言言不不限):
1 1 2 3 5 8 13 21 34 55 ....


def fib(num):
    a, b, count = 0, 1, 1  # 0, 1
    while count <= num:
        print(b)
        a, b = b, a + b  #a=2, b=3
        count += 1


fib(10)

第四题:将一个英文语句以单词为单位逆序排放。例如“I am a boy”,逆序排放后为“boy a am I”所有单词之间 用一个空格隔开,语句中除了英文字母外,不再包含其他字符       - 输入描述:将一个英文语句以单词为单位逆序排放。
       - 输出描述:得到逆序的句子
示例1:
    - 输入
    I am a boy
    - 输出

    boy a am I

s = 'I am a boy'
a = " ".join(s.split()[::-1])
print(a)

第五题:

用 filer()进行函数式编程,写一段代码来给出一个年份的列表并返回一个只有闰年的列表。列表解析式实现方式呢?

def Judge_Leap_Year(*args):                                                                        
    for Year_num in args:                                                                          
        if (Year_num % 4 == 0 and Year_num % 100 != 0) or Year_num % 400 == 0:                     
            return True                                                                            
        else:                                                                                      
            return False                                                                         
             
                                                                                                   
list_year = [1996,2000,2004,2008,2010,2050,2018]                                                   
print(list(filter(Judge_Leap_Year,list_year)))                                                    
                                                                                                   
                                                                                                   

第六题:

列表和字典复习.给出一个整数值,返回代表该值的英文,比如输入 89 返回"eight-nine"。附加题:

能够返回符合英文语法规则的形式,比如输入“89”返回“eighty-nine”。本练习中的值限定在家 0到 1,000

def fun1(nums):                                                          
    str1=''                                                              
    lis1=[str(i) for i in range(1,10)]                                   
    lisA=['one','two','three','four','five','six','seven','eight','nine']
    lis=list(str(nums))                                                  
    for i in lis:                                                        
        str1 +=lisA[lis1.index(i)]+'-'                                   
                                                                         
                                                                         
    print('The Result is:',str1[:-1])                              
fun1(89)                                                                 

第七题:

a)给出两个可识别格式的日期,比如 MM/DD/YY 或者 DD/MM/YY 格式,计算出两个日期间的天数.

from datetime import date


def calcdate(string1, string2):
    temp_list1 = string1.split("/")
    temp_list2 = string2.split("/")
    days_count = ""
    first_date = date(int(temp_list1[2]), int(temp_list1[1]), int(temp_list1[0]))
    second_date = date(int(temp_list2[2]), int(temp_list2[1]), int(temp_list2[0]))
    if first_date < second_date:
        days_count = abs(second_date - first_date)
    return days_count.days
calcdate()

b)给出一个人的生日,计算从此人出生到现在的天数,包括所有的闰月.

import datetime

brithday = input('YY-MM-DD:')
print(datetime.datetime.now() - datetime.datetime.strptime(brithday,'%Y-%m-%d'))

c)还是上面的例子,计算出到此人下次过生日还有多少天.

第八题:

文件访问. 写一个逐页显示文本文件的 程序. 提示输入一个文件名, 每次显示文本
文件的 25 行, 暂停并向用户提示"按任意键继续.", 按键后继续执行.

注意:文件结束处理

def check_file():                           
    fname=input("Enter filename:").strip()  
    fp = open(fname,'r')                    
    while True:                             
        lines=0                             
        for p in range(25):                 
            cline=fp.readline()             
            if cline!='':                   
                lines+=1                    
                print(cline,)               
        if lines<25:                        
            print ('\nfile is over')        
            break                           
        info=input("continue?(Y/N)").upper()
        if info=='N':                       
            break                           
    fp.close()                              
                                            
check_file()                                

猜你喜欢

转载自blog.csdn.net/biu_biu_0329/article/details/80362198