Python Course Design Note 9 of 52

Function Overview - Reference Answers

Assignment 1

Write a function where the user passes in the name of the file to modify and the content to modify; executing the function completes the modification

Reference approach:

image.png

import os

def modify_file(file_name, old_content, new_content):
    with open(file_name, mode='rt', encoding='utf-8') as read_f, \
            open('%s.swap' % file_name, mode='wt', encoding='utf-8') as write_f:
        for line in read_f:
            if old_content in line:
                line = line.replace(old_content, new_content)

            write_f.write(line)

    os.remove(file_name)
    os.rename('%s.swap' % file_name, file_name)

modify_file('db.txt', '马一特', '马一特[Albert]')

Assignment 2

Write a function that counts the number of [digits], [letters], [spaces] and [others] in the string passed in

Reference approach:

You can use string methods such as isalpha() to determine whether a character is a letter or a space;

There is another method: since the ASCII codes of lowercase and uppercase letters are both contiguous, you can use two lists to represent AZ and az, then use char in lst to check. Give it a try.

image.png

def calculate_count(data_str):
    dict_count = {'alpha': 0, 'number': 0, 'space': 0, 'other': 0}
    for i in data_str:
        if i.isalpha():
            dict_count['alpha'] += 1
        elif i.isdigit():
            dict_count['number'] += 1
        elif i is ' ':
            dict_count['space'] += 1
        else:
            dict_count['other'] += 1
    return dict_count

res = calculate_count('32441adhjf  ^&%$#@()*')
print(res)

Assignment 3

Write a function that checks whether the length of the object passed in by the user (string, list, tuple) is greater than 5.

Reference approach:

image.png

def judge_length(data):
    if len(data) > 5:
        return True
    else:
        return False

res1 = judge_length('sahdlfk')
res2 = judge_length([12, 2, 3, ])
res3 = judge_length((2, 3, 4, 5, 6, 5,))
print(res1)
print(res2)
print(res3)

Assignment 4

Write a function that checks the length of the list passed in; if it is greater than 2, keep only the first two items and return the new content to the caller.

Reference approach:

image.png

def check_up_list(data_list):
    if len(data_list) > 2:
        return data_list[:2]

res1 = check_up_list([1, 2, 3, 4, 4, 5, ])
res2 = check_up_list(['a', 'v', 'v', 'e'])
res3 = check_up_list(['x', ])

print(res1)
print(res2)
print(res3)

Assignment 5

Write a function that gets the elements at all odd indices of the list or tuple object passed in, and returns them to the caller as a new list.

Reference approach:

image.png

def get_odd_list(data):
    odd_list = []
    for i in data:
        if data.index(i) % 2:
            odd_list.append(i)
    return odd_list

print(get_odd_list([1, 2, 3, 4, ]))
print(get_odd_list((13, 4322, 2333, 114,)))
print(get_odd_list(['a', 'b', 'c', 'd']))

Assignment 6

Write a function that checks the length of each value in a dictionary; if it is greater than 2, keep only the first two items and return the new content to the caller.

dict1 = {"k1": "v1v1", "k2": [11, 22, 33, 44], 'k3': (9, 8, 7, 65, 4)}

Approach:

Combine Assignments 4 and 5 with the method of iterating over a dictionary’s keys and values.

dict1 = {"k1": "v1v1", "k2": [11, 22, 33, 44], 'k3': (9, 8, 7, 65, 4)}

def check_up_list(data_dict):
    for key, value in data_dict.items():
        if len(value) > 2:
            data_dict[key] = value[:2]
    return data_dict

res = check_up_list(dict1)
print(res)