Python basic programming questions - exercise 1

topic one

The first two terms of the Fibonacci sequence are both 1. Starting with the third term, each term is the sum of the previous two.
That is: 1, 1.2, 3, 5, 8, ... Write a program to use the list to calculate:
1) The first 30 items of the Fibonacci sequence and output
2) The items within 1000 of the Fibonacci sequence and output

problem solving ideas

The first two terms of the Fibonacci sequence are both 1. Starting with the third term, each term is the sum of the previous two. This question requires the calculation of the first 30 items and the Fibonacci sequence less than or equal to 1000, which can be realized by using a list and a loop structure. When calculating the first 30 items, define a list of length 2 to save the first two items, and then calculate the remaining items in the list through a loop. When calculating the Fibonacci sequence less than or equal to 1000, you can also define an array to save the first two items, and use a while loop to calculate the Fibonacci sequence less than or equal to 1000.

Code

# 计算前30项
fibonacci_list = [1, 1]
for i in range(2, 30):
    fibonacci_list.append(fibonacci_list[i-1] + fibonacci_list[i-2])
print('前30项斐波那契数列为:', fibonacci_list)

# 计算小于等于1000的所有项
fibonacci_list = [1, 1]
a, b = 1, 1
while a + b <= 1000:
    a, b = b, a + b
    fibonacci_list.append(b)

print('小于等于1000的斐波那契数列为:', fibonacci_list)

run screenshot

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-q1r3RvLy-1684573333432) (C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\ image-20230519105842909.png)]

Topic 2

There are two files, priceA.txt and priceB.txt, which respectively store the unit price information of pharmacy A and pharmacy B. It is required to merge the drug prices of pharmacy B with those of pharmacy A, and output them in descending order according to the length of drug names, and the prices are also required to be aligned. . If the drug name exists in both pharmacy A and pharmacy B, the price in pharmacy A shall prevail. If there is a drug in pharmacy B that does not appear in pharmacy A, the original price in pharmacy B will remain unchanged.

problem solving ideas

We can use Python's dictionary data structure to store drug and unit price information. First read the priceA.txt file, and store the drug and unit price information in a dictionary. Next, read the priceB.txt file and merge according to the title requirements: if the drug exists in both pharmacy A and pharmacy B, use the price of pharmacy A; if the drug only exists in pharmacy B, then combine the drug with the unit price The information is added to the dictionary; if the drug exists only in Pharmacy A, nothing needs to be done. Finally, we can output the drug and price information in the dictionary in descending order according to the length of the drug name, and we need to pay attention to the alignment of prices.

Code

# 读取药房A的药品和单价信息
price_a = {
    
    }
with open('priceA.txt', encoding='utf-8') as f:
    for line in f.readlines():
        name, price = line.strip().split(',')
        price_a[name] = float(price)

# 合并药房B的药品和单价信息
price_b = {
    
    }
with open('priceB.txt', encoding='utf-8') as f:
    for line in f.readlines():
        name, price = line.strip().split(',')
        if name in price_a:
            price_b[name] = price_a[name]
        else:
            price_b[name] = float(price)

# 将两个字典合并
price = {
    
    **price_a, **price_b}

# 按药品名称长度降序排序并输出
print('{:^20} {:^10}'.format('药品名称', '单价'))
print('-' * 30)
for name, price in sorted(price.items(), key=lambda x: len(x[0]), reverse=True):
    print('{:<20} {:>10.2f}'.format(name, price))

run screenshot

insert image description here

Topic three

Write a program, read a python source program file, replace all lowercase letters in the file except reserved words with uppercase letters, and the generated file must be able to be executed correctly by the python interpreter.

topic analysis

This question requires writing a program that reads a python source program file and replaces all lowercase letters in the file except reserved words with uppercase letters. The generated file must be able to be executed correctly by the Python interpreter.

In order to implement this program, we need to analyze each small problem step by step. The specific analysis is as follows:

  1. How to view all reserved words in Python?
    • All reserved words in Python are stored in the keyword module. We can get the list of reserved words by importing this module and calling the kwlist variable it provides.
  2. How to read the contents of a Python source file?
    • We can use the Python built-in function open() to open a Python source file, and then use the read() method to read the file content.
  3. How to parse the content of the source file into an AST tree?
    • The ast module in the Python standard library provides the function of parsing Python code into AST (abstract syntax tree). We can use the parse() function in this module to parse the file into an AST tree.
  4. How to modify the identifier name in the AST tree?
    • In AST, identifiers are usually represented as Name nodes. We can traverse the entire AST tree, find the Name node, and then modify its id attribute (that is, the identifier name) as needed.
  5. What to do with built-in method names?
    • Some built-in method names are both reserved words and built-in functions. We have to treat these identifiers specially, and we cannot convert all their names to uppercase, otherwise the program will go wrong.
  6. How to regenerate the modified code into a string and write it into a new file?
    • After modifying the nodes in the AST tree, we need to regenerate the modified code into a string form. This can be done using the unparse() function in the ast module, which converts the modified AST tree back to a Python source program string. Then, we can write the modified code into a new file.

After the above analysis, we can start writing programs. The specific problem-solving ideas and code implementation are as follows.

problem solving ideas

  1. Read the content of the source file and parse it into an AST tree.
  2. Traverse all identifiers in the AST tree, and perform case conversion on lowercase identifiers that are not reserved words.
  3. Regenerate the modified AST tree into a Python source program string.
  4. Write the modified string to a new file.

Code

import ast
import keyword


# 将标识符名称按照需要进行大小写转换
def normalize_name(name):
    if not keyword.iskeyword(name) and not hasattr(__builtins__, name):
        return name.upper()
    return name


# 将函数定义中的参数列表进行大小写转换
def normalize_arguments(args):
    for arg in args.args:
        arg.arg = normalize_name(arg.arg)


# 打开源文件并读取源代码
with open('源程序.py', 'r', encoding='utf-8') as source_file:
    source_code = source_file.read()

# 将源代码解析成AST树
root = ast.parse(source_code)

# 对AST树中的标识符进行修改
for node in ast.walk(root):
    if isinstance(node, ast.Name):
        node.id = normalize_name(node.id)
    elif isinstance(node, ast.FunctionDef):
        node.name = normalize_name(node.name)
        normalize_arguments(node.args)
    elif isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name):
        if not keyword.iskeyword(node.attr) and not hasattr(__builtins__, node.attr):
            node.attr = node.attr.upper()
            node.value.id = node.value.id.upper()

# 重新生成修改后的代码
modified_code = ast.unparse(root)

# 打开目标文件并写入修改后的代码
with open('新文件.py', 'w', encoding='utf-8') as target_file:
    target_file.write(modified_code)

run screenshot

insert image description here

Guess you like

Origin blog.csdn.net/m0_67268191/article/details/130783529