Python Chapter 6 Homework

Table of contents

Level 1 List properties and methods

Level 2 Comprehensions and Generators

Level 3 Merge and sort lists

Level 4 Sorting Two-Dimensional Lists

Level 5 Sorting Animals by Weight

Level 6 ID card number upgrade

Level 7 Perfect Cube

Level 8 Joseph Ring Problem

Level 9 Text Analysis (2) - counting the number of words in English documents


Level 1 List properties and methods

Initialize an empty list, input a positive integer n. Next, you will be asked to input n instructions, and after each instruction, perform the corresponding functional operation according to the instruction string. The command form and corresponding function are as follows:

  1. insert i e: # 在第 i 个位置插入整数 e。
  2. print: # 输出列表
  3. remove e: # 删除第一次出现的整数 e .
  4. append e: # 在列表的末尾插入整数 e.
  5. sort: # 按默认规则排序.
  6. pop: # 弹出列表最后一一个元素
  7. reverse: # 列表元素逆序
list = []
n = int(input())
for i in range(n):
    a = input().split()
    if a[0] == 'insert':
        list.insert(int(a[1]),int(a[2]))
    elif a[0] =='append':
        list.append(int(a[1]))
    elif a[0] =='remove':
        list.remove(int(a[1]))
    elif a[0] =='sort':
        list.sort()
    elif a[0] =='pop':
        list.pop()
    elif a[0] =='reverse':
        list = list[::-1]
    elif a[0] =='print': 
        print(list)

Level 2 Comprehensions and Generators

Comprehensions can construct another new data sequence structure from one data sequence. In essence, it can be understood as a function that combines transformation and filtering functions, through which one sequence is converted into another sequence. ‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬ ‪‬‪‬‪‬‪‬‮‬‪‬‪‬

ls = ['the lord of the rings','anaconda','legally blonde','gone with the wind']
s = input()        # 输入一个字符
# 当输入为"1"时,输出元素为0-9的3次方的列表 [0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
if s == '1':
    print([x**3 for x in range(10)])
# 当输入为"2"时,输出元素为0-9中偶数的3次方的列表 [0, 8, 64, 216, 512]
elif s == '2':
    list =[]
    for i in range(10):
        if i%2==0:
            x= i**3
            list.append(x)
    print(list)
 # 当输入为"3"时,输出元素为元组的列表,元组中元素依次是0-9中的奇数和该数的3次方[(1, 1), (3, 27), (5, 125), (7, 343), (9, 729)]
elif s == '3':
    list =[]
    for i in range(10):
        if i%2!=0:
            x=tuple((i,i**3))
            list.append(x)
    print(list)

# 当输入为"4"时,将ls中每个元素单词首字母大写输出['The lord of the rings', 'Anaconda', 'Legally blonde', 'Gone with the wind']
elif s == '4':
    print([list.strip().capitalize() for list in ls])
# 当输入为其他字符时,执行以下语句
else:
    print('结束程序')

Level 3 Merge and sort lists

Read in two lines with the same format, which are several integers separated by spaces, combine these numbers into a list, and output the entire list after sorting in descending order. ‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬ ‪‬‪‬‪‬‪‬‮‬‪‬‪‬

hint:list1 = list(map(int,input().split())) #读入一行由空格分隔的整数,将其存入list1列表中

list1 = list(map(int,input().split()))
list2 = list(map(int,input().split()))
list3 = list1 + list2 
list3.sort(reverse = True)
print(list3)

Level 4 Sorting Two-Dimensional Lists

There are the following two two-dimensional lists. The elements of the first list are tuples, please sort and output them according to the second element value of the list elements from small to large, and output the first m items; ‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬

List one:[('dungeon',7),('winterfell',4),('bran',9),('meelo',6)]‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬

The elements of the second list are still lists, please sort them according to the value of the first and third elements of each element from small to large, and output the first n items. ‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬ ‪‬‪‬‪‬‪‬‮‬‪‬‪‬

List two:[[ 'Angle', '0121701100106',99], [ 'Jack', '0121701100107',86], [ 'Tom', '0121701100109',65], [ 'Smith', '0121701100111', 100], ['Bob', '0121701100115',77], ['Lily', '0121701100117', 59]]

m and n are non-negative integers input by the user. When m or n is greater than the length of the list, the entire list will be sorted and output. ‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬ ‪‬‪‬‪‬‪‬‮‬‪‬‪‬

list1 = [('dungeon',7),('winterfell',4),('bran',9),('meelo',6)]
list2 = [['Angle', '0121701100106',99], ['Jack', '0121701100107',86], ['Tom', '0121701100109',65], ['Smith', '0121701100111', 100], ['Bob', '0121701100115',77], ['Lily', '0121701100117', 59]]
list3 = sorted(list1,key = lambda x: x[1])
list4 = sorted(list2,key = lambda x: x[0])
list5 = sorted(list2,key = lambda x: x[2])
m = int(input())
n = int(input())
print(list3[:m])
print(list4[:n])
print(list5[:n])

Level 5 Sorting Animals by Weight

Enter a series of animal names and their weights. The weight unit may be kg or t. There is a space between the animal name and the weight, and there is no separation between the weight value and the unit. Sort by weight from small to large and output in the form of a two-dimensional list.

input format ‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬

Each time you input an animal name, and its weight and unit, the animal name and weight are separated by a space, and the input ends when you directly enter the carriage return (at this time, the input character is an empty string).

Tip: Determine whether the input is ''an empty string, and if Trueso, end the input.

list1 = []
while True:
    a = input().split()
    if len(a) == 0:
        break
    else:
        list1.append(a)
list2 = sorted(list1,key = lambda x: float(x[1][:-1])*1000 if x[1][-1]=="t" else float(x[1][:-2]))
print(list2)

Level 6 ID card number upgrade

The second-generation resident identity card is implemented in accordance with the "Law of the People's Republic of China on Resident Identity Cards" passed at the third meeting of the Standing Committee of the Tenth National People's Congress on June 28, 2003. The general rules for upgrading the fifteen-digit number of the first-generation ID card to the eighteen-digit number of the second-generation ID card are: ‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬

19The first step is to insert (born after January 1, 1905) or 20(born 2000.1.1-2004.12.31) after the sixth digit of the original 15-digit ID card , so that the ID number is 17 digits ; The second step is to calculate the eighteenth digit according to the unified formula stipulated by the state, and put it on the tail number of the second-generation ID card as a check code. ‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬ ‪‬‪‬‪‬‪‬‮‬‪‬‪‬

Check code calculation method: multiply the first 17 digits of the ID card by different coefficients and sum S = Sum(Ai * Wi) Ai: represent the digital value of the ID card number at the i-th position, i = 0, ... , 16 Wi: represent the weighting factor at the i-th position, and get the modulus of Wi: 7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2S 11The remainder 0-10, the corresponding check code is as follows: Remainder Y: 0 1 2 3 4 5 6 7 8 9 10check code:1 0 X 9 8 7 6 5 4 3 2‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬

The title assumes that all people were born after January 1, 1905 and before January 1, 2005

n = input()
list1 = list(n)
Wi=[7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2]
if int(list1[6])+int(list1[7]) >= 5:
    list1.insert(6,9)
    list1.insert(6,1)
else:
    list1.insert(6,0)
    list1.insert(6,2)
s = 0
for i in range(17):
    s +=  int(list1[i]) * int(Wi[i])
m = s % 11
list2 = [1,0,'X',9,8,7,6,5,4,3,2]
list1.append(list2[m])
for x in list1:
    print(*str(x),end = '')

Level 7 Perfect Cube

Fermat's last theorem asserts that, for integers n > 2, the equations for a, b, and c an= bn + cnhave no positive integer solutions. After the theorem was proposed, it took more than 300 years and many conjectures and dialectics, and was finally proved by the British mathematician Andrew Wiles in 1995. However, it is possible to find 4 integers greater than 1 that satisfy the perfect cubic equation: a3 = b3 + c3 + d3(for example 123 = 63 + 83 + 103) Write a program that, for any given positive integer N (N<=100), finds all four-tuples (a,b,c ,d), satisfy a3 = b3 + c3 + d3(where 1 < a,b,c,d <=N)

N = int(input())
for a in range(2,N+1):
    for b in range(2,a):
        for c in range(b,a):
            for d in range(c,a):
                if a**3 == b**3+c**3+d**3:
                    print(f'Cube = {a},Triple = ({b},{c},{d})')

Level 8 Joseph Ring Problem

It is said that the famous historian Josephus had the following story: Josephus and his friends formed a circle with a total of 41 people, and the first person began to count. Count until there are less than 3 people on the circle. Josephus placed his friend and himself in 16th and 31st, the last remaining players. ‪‬‪‬‪‬‪‬‪‬‮‬‪‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬ ‪‬‪‬‪‬‪‬‮‬‪‬‪‬

To expand this problem, when the number of people is n and each report is k, find the position of the last K-1 remaining people

n,k =map(int,input().split())
ls1 = [i for i in range(1,n+1)]
num = 0
if k < 2 or n < k :
    print('Data Error!')
else:
    while len(ls1) >= k:
        num +=1
        count = ls1.pop(0)
        if num % k != 0:
            ls1.append(count)
    print(ls1)

Level 9 Text Analysis (2) - counting the number of words in English documents

Tip: When counting the number of words, the abbreviated forms such as It’s, Let's, don'tshould be counted as 2 words. In addition, for the convenience of processing, it is agreed that there is no 's in all test files to indicate the possessive case.

example ‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬

enter:mySunshine.txt

output:共有7个单词

def read_file(file):
    """接收文件名为参数,读取文件中的数据到字符串中,返回这个字符串"""
    with open(file, 'r', encoding='utf-8') as text:  # 创建文件对象
        txt =text.read()      # 读文件为字符串
    return txt     # 返回字符串


def word_list(txt):
    """接收字符串为参数,用空格替换字符串中所有标点符号,根据空格将字符串切分为列表
    返回值为元素为单词的列表"""
    for i in ",.!\'":
        txt = txt.replace(i, ' ')
    return txt.split()


def number_of_words(ls):
    """接收一个以单词为元素的列表为参数,返回列表中单词数量,返回值为整型"""
    return len(ls)


if __name__ == '__main__':
    filename = input()                          # 读入文件名
    text = read_file('step10/'+filename)        # 读取'step10/'文件夹中用户输入的文件名得到文件内容,存入text
    words_list = word_list(text)                # 处理text,得到单词的列表
    words_counts = number_of_words(words_list)  #统计单词列表word_list里的单词数
    print(f'共有{words_counts}个单词')

Guess you like

Origin blog.csdn.net/m0_70456205/article/details/130253549