Exercise 10 in 2020 Python -- parameters of functions

Posted by Timma on Wed, 18 Mar 2020 15:28:53 +0100

@2020.3.18 

1. Write function, the user passes in the modified file name, and the content to be modified, executes the function, and completes the batch modification operation

def modify_file(filename,old,new):
    import os
    with open(filename,'r',encoding='utf-8') as read_f,\
        open('.bak.swap','w',encoding='utf-8') as write_f:
        for line in read_f:
            if old in line:
                line=line.replace(old,new)
            write_f.write(line)
    os.remove(filename)
    os.rename('.bak.swap',filename)


2. Write a function to calculate the number of [numbers], [letters], [spaces] and [Others] in the incoming string

def check_str(msg):
    res={
        'num':0,
        'string':0,
        'space':0,
        'other':0,
    }
    for s in msg:
        if s.isdigit():
            res['num']+=1
        elif s.isalpha():
            res['string']+=1
        elif s.isspace():
            res['space']+=1
        else:
            res['other']+=1
    return res

 

3. Write function to determine whether the length of the object (string, list, tuple) passed in by the user is greater than 5.  

def len_check(inp):
    if len(inp) >5:
        print('The length of the object entered exceeds the limit')
    else:
        print('The length of the input is:{}'.format(len(inp)))

len_check('aaaaa')

 

4. Write a function to check the length of the incoming list. If it is greater than 2, only the first two lengths of content will be retained and the new content will be returned to the caller.  

def list_check(inp_list):
    if len(inp_list) >2:
        inp_list=inp_list[0:2]
    return inp_list

print(list_check([1,4,7,9]))

 

5. Write function, check to get all the odd index elements of the incoming list or tuple object, and return them to the caller as a new list.  

def list_check2(seq):
    return seq[::2]

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

 

6. Write a function to check the length of each value in the dictionary. If it is greater than 2, only the first two length contents will be retained and the new contents will be returned to the caller.
dic = {"k1": "v1v1", "k2": [11,22,33,44]}
PS: value in dictionary can only be string or list

def dic_check(inp_dic):
    d={}
    for a,b in dic.items():
        if len(b) >2:
            d[a]=b[0:2]
    return d

dic = {"k1": "v1v1", "k2": [11,22,33,44]}
print(dic_check(dic))

Topics: Python encoding