浙大版《Python程序设计》题目集(第六章)

第6章-1 输入列表,求列表元素和(eval输入应用)

ls = eval(input())
sum = 0
for t in ls:
    sum = sum + t
print(sum)

第6章-2 一帮一

num = eval(input())
count = 1
students = []
match = []
cnt = 0
while count <= num:
    stu = input().split(" ")
    students.append(stu)
    count = count + 1
start = 0
end = len(students) - 1
while start < end:
    if students[start][0] != students[end][0]:
        match.append(students[start][1])
        match.append(students[end][1])
        students.pop(end)
        start = start + 1
        end = len(students) - 1
    else:
        end = end - 1
for t in match:
    cnt = cnt + 1
    if cnt % 2 == 0:
        print(t)
    else:
        print(t,end = ' ')

第6章-3 列表或元组的数字元素求和

strs = input()
strs = strs.replace("["," ")
strs = strs.replace("]"," ")
strs = strs.replace("("," ")
strs = strs.replace(")"," ")
strs = strs.replace(","," ")
s = ''
flag = 0
sum = 0
for str in strs:
    if str == '"':
        flag = flag + 1
    if flag % 2 == 0 and str != '"':
        s = s + str
        print(s)
s = s.split()
for t in s:
    sum = sum + int(t)
print(sum)

第6章-4 列表数字元素加权和(1)

#采用递归思想实现
def deep_sum(ls,deep):
    sum = 0
    for i in ls:
        if isinstance(i,int):
            sum = sum + i * deep
        elif isinstance(i,list):
            sum = sum + deep_sum(i,deep + 1)
    return sum
ls = eval(input())
print(deep_sum(ls,1))

第6章-5 列表元素个数的加权和(1)

def count_list(ls,deep):
    count = 0
    for i in ls:
        if not isinstance(i,list):
            count = count + 1 * deep
        elif isinstance(i, list):
            count = count + count_list(i,deep + 1)
    return count
ls = eval(input())
print(count_list(ls,1))

第6章-6 求指定层的元素个数

def count_num(ls,deep):
    count = 1
    num = 0
    for i in ls:
        if isinstance(i,list):
            count = count  + 1
            if count == deep:
                num = num + len(i)
                break
            else:
                num = num + count_num(i,deep - 1)
        else:
            if count == deep:
                num = num + len(ls)
                break
    return num
ls = eval(input())
deep = eval(input())
print(count_num(ls,deep))

第6章-7 找出总分最高的学生

num = eval(input())
count = 1
ls = []
sum_max = 0
index = 0
while count <= num:
    info = input().split(" ")
    ls.append(info)
    count = count + 1
sum_max = sum_max + int(ls[0][2]) + int(ls[0][3]) + int(ls[0][4])
for i in range(1,len(ls)):
    if int(ls[i][2]) + int(ls[i][3]) + int(ls[i][4]) > sum_max:
        sum_max = int(ls[i][2]) + int(ls[i][3]) + int(ls[i][4])
        index = i
print(ls[index][1],ls[index][0],sum_max,end = '')

第6章-8 输出全排列

def all_sort(i,s = ""):
    s = s + i
    if len(s) < num:
        for j in strs:
            if j not in s:
                all_sort(j,s)
    else:
        print(s)
num = eval(input())
strs = [str(i + 1) for i in range(num)]
for i in strs:
    all_sort(i)
posted @ 2021-10-27 20:53  闲晚  阅读(154)  评论(0编辑  收藏  举报