计算机二级Python编程题记录(下)

简介: 计算机二级Python编程题记录

第十三套


1




n = input('请输入一个正整数:')
for i in range(1,eval(n)+1):
    print('{:0>2}{}'.format(i, '>'*i))


2




ns = input("请输入一串数据:")
dnum,dchr = 0,0
for i in ns:
    if i.isnumeric():
        dnum += 1
    elif i.isalpha():
        dchr += 1
    else:
        pass
print('数字个数:{},字母个数:{}'.format(dnum, dchr))


3




std = [['张三',90,87,95],['李四',83,80,87],['王五',73,57,55]]
modl = "亲爱的{}, 你的考试成绩是: 英语{}, 数学{}, Python语言{}, 总成绩{}.特此通知."
for st in std:
    cnt = 0
    for i in range(1,4):
        cnt += st[i]
    print(modl.format(st[0],st[1],st[2],st[3],cnt))


4



import turtle as t
import random as r
color = ['red','orange','blue','green','purple']
r.seed(1)
for i in range(5):
    rad = r.randint(20,50)
    x0 = r.randint(-100,100)
    y0 = r.randint(-100,100)
    t.color(r.choice(color))
    t.penup()
    t.goto(x0,y0)
    t.pendown()
    t.circle(rad)
t.done()


5




img = [0.244, 0.832, 0.903, 0.145, 0.26, 0.452]
filter = [0.1,0.8,0.1]
res = []
for i in range(len(img)-2):
    k = 0
    for j in range(len(filter)):
        k += filter[j] * img[j+i]
        print("k={:.3f} ,filter[{}]={:.3f} ,img[{}{}{}]={:.3f}".format(k,j,filter[j],i,'+',j,img[i+j]))
    res.append(k)
for r in res:
    print('{:<10.3f}'.format(r),end = '')


6



import jieba
fi = open("data.txt","r",encoding='utf-8')
data = fi.read()
fo = open("clean.txt","w")
s = ''
except_word = ",。?、‘’“”;:()\n--!"
for i in data:
    if i not in except_word:
        s += i
fo.write(s)
fi.close()
fo.close()


import jieba
fi = open("clean.txt", "r")
data = fi.read()
words = jieba.lcut(data)
d = {}
for word in words:
    if len(word)>=3:
        d[word] = d.get(word, 0) + 1
lt = list(d.items())
lt.sort(key=lambda x: x[1], reverse=True)
for i in lt[:9]:
    print(i[0], ":", i[1], end=',', sep='')
print(lt[9][0], ":", lt[9][1], sep='')
fi.close()


第十四套


1




s = input()
print("{:\"^30x}".format(eval(s)))


2




n = input()
s = "〇一二三四五六七八九"
for c in "0123456789":
     n = n.replace(c, s[eval(c)])
print(n)


3




a, b, c = [eval(x) for x in input().split(",")]
ls = []
for i in range(c):
    ls.append(str(a*(b**i)))
print(",".join(ls))


4




import turtle
turtle.pensize(2)
for i in range(4):
    turtle.fd(200)
    turtle.left(90)
turtle.left(-45)
turtle.circle(100*pow(2,0.5))


5




while True:
    s = input("请输入不带数字的文本:")
    for i in s:
        if i in '0123456789':
            break
    else:
        break
print(len(s))


6



fi = open("data.txt", "r")
f = open("univ.txt", "w")
L = []
lines = fi.readlines()
for line in lines:
    if 'alt=' in line:
        begin = line.find('alt=')
        end = line.find('"', begin + 5)
        L.append(line[begin + 5:end])
for i in L:
    f.write(i + "\n")
fi.close()
f.close()


# 请在______处使用一行或多行代码替换
#
# 注意:其他已给出代码仅作为提示,可以修改
f = open("univ.txt", "r")
n = 0   # 包含大学的名称数量
m = 0
L = []
names = f.readlines()
for name in names:
    name = name.strip("\n")
    if "大学生" not in name:
        if "大学" in name:
            L.append(name)
        elif "学院" in name:
            L.append(name)
for name in L:
    if name[-2:] == "学院":
        m += 1
    else:
        n += 1
    print(name)
f.close()
print("包含大学的名称数量是{}".format(n))
print("包含学院的名称数量是{}".format(m))


第十五套


1




n = eval(input("请输入正整数:"))
print("{:=^14}".format(n))


2




a = [3, 6, 9]
b = eval(input())  # 例如:[1,2,3]
j = 1
for i in range(len(a)):
    b.insert(j, a[i])
    j += 2
print(b)


3




import random
random.seed(100)  # 此处可多行
s = 0   
for i in range(3):
    a = random.randint(1, 9)
    s += a ** 3
print(s)


4




import turtle
turtle.pensize(2)
d = 0
for i in range(1, 6):
    turtle.fd(100)
    d += 72
    turtle.seth(d)


5



f = open("vote.txt")
names = f.readlines()
f.close()
n = 0
for name in names:
    num = len(name.split())
    if num == 1:
        n += 1
print("有效票{}张".format(n))


f = open("vote.txt")
names = f.readlines()
f.close()
L = []
for name in names:
    num = len(name.split())
    if num == 1:
        L.append(name.strip("\n"))
d = {}
for name in L:
    d[name] = d.get(name,0) + 1
ls = list(d.items())
ls.sort(key=lambda x:x[1], reverse=True) # 此行可以按照词频由高到低排序
print("{}:{}".format(ls[0][0],ls[1][1]))


6



# 请在...处使用多行代码替换
#
# 注意:其他已给出代码仅作为提示,可以修改
import jieba
fi = open("data.txt", "r")
f = open('out1.txt', 'w')
txt = fi.read()
words = jieba.lcut(txt)
words = list(set(words))
for word in words:
    if len(word)>=3:
        f.write(word+"\n")
fi.close()
f.close()


import jieba
fi = open("data.txt", 'r')
fo = open('out2.txt', 'w')
txt = fi.read()
words = jieba.lcut(txt)
d = {}
for word in words:
    if len(word) >= 3:
        d[word] = d.get(word, 0) + 1
ls = list(d.items())
ls.sort(key=lambda x: x[1], reverse=True)  # 此行可以按照词频由高到低排序
for i in ls:
    a = i[0]+":"+str(i[1])
    fo.write(a+"\n")
fi.close()
fo.close()


第十六套


1




s = input("请输入一个正整数: ")
cs = 0
for c in s:
    cs += eval(c)
print('{:=^25}'.format(cs))


2




s = input("请输入中文和字母的组合: ")
count = 0
for c in s:
    if '\u4e00' <= c <= '\u9fff':
        count += 1
print(count)


3




s = input("请输入一组数据: ")
ls = s.split(',')
lt = []
for i in ls:
    lt.append(eval(i))
print(max(lt))


4



import turtle as t
import random as r
r.seed(1)
t.pensize(2)
t.pencolor('red')
angles = 6
points= [[0,0],[50,40],[70,80],[-40,30]]
for i in range(4):
    x0,y0 = points[i]
    t.penup()
    t.goto(x0,y0)
    t.pendown()
    length = r.randint(6, 16)
    for j in range(angles):
        t.fd(length)
        t.backward(length)
        t.right(360 / angles)
t.done()


5




f = open('data.txt','r')
dic={}
for line in f:
    l=line.strip().split(',')
    if len(l)<3:
        continue
    dic[l[-1]]=dic.get(l[-1],[])+[l[1]]
unis=list(dic.items())
unis.sort(key=lambda x:len(x[1]),reverse=True)
for d in unis:
print('{:>4}: {:>4} : {}'.format(d[0],len(d[1]),' '.join(d[1]))) 


6



import jieba
f = "红楼梦.txt"
sf = "停用词.txt"
f1 = open(f, "r", encoding='utf-8')
datas = f1.read()
f1.close()
f2 = open(sf, "r", encoding='utf-8')
words = f2.read()
f2.close()
data = jieba.lcut(datas)
d = {}
word = ["一个", "如今", "一面", "众人", "说道", "只见", "不知",
        "两个", "起来", "二人", "今日", "听见", "不敢", "不能",
        "东西", "只得", "心中", "回来", "几个", "原来", "进来",
        "出去", "一时", "银子", "起身", "答应", "回去"]
for i in data:
    if len(i) < 2 or i in words or i in word:
        continue
    if i in ['凤姐', "凤姐儿", "凤丫头"]:
        i = "凤姐"
    elif i in ["宝玉", "二爷", "宝二爷"]:
        i = "宝玉"
    elif i in ["黛玉", "颦儿", "林妹妹", "黛玉道"]:
        i = "黛玉"
    elif i in ["宝钗", "宝丫头"]:
        i = "宝钗"
    elif i in ["贾母", "老祖宗"]:
        i = "贾母"
    elif i in ["袭人", "袭人道"]:
        i = "袭人"
    elif i in ["贾政", "贾政道"]:
        i = "贾政"
    elif i in ["贾琏", "琏二爷"]:
        i = "贾琏"
    d[i] = d.get(i, 0) + 1
l = list(d.items())
l.sort(key=lambda x: x[::-1], reverse=True)
f = open("result.csv", "w")
for i in l:
    if i[1] < 40:
        break
    f.write(i[0] + ',' + str(i[1]) + '\n')
f.close()


第十七套


1




s = input("请输入一个小数: ")
s = s[::-1]
cs = 0
for c in s:
    if c == '.':
        break
    cs += eval(c)
print('{:*>10}'.format(cs))


2




import time
t = input("请输入一个浮点数时间信息: ")
s = time.ctime(eval(t))
ls = s.split()
print(ls[3].split(':')[0])


3



import random
s = input("请输入随机种子: ")
ls = []
for i in range(26):
    ls.append(chr(ord('a')+i))
for i in range(10):
    ls.append(chr(ord('0')+i))
random.seed(eval(s))
for i in range(10):
    for j in range(8):
        print(ls[random.randint(0,35)],end='')
    print()


4




import turtle as t
import random as r
r.seed(1)
t.pensize(2)
for i in range(3):
    length = r.randint(20,80)
    x0 = r.randint(-100, 100)
    y0 = r.randint(-100, 100)
    t.penup()
    t.goto(x0,y0)
    t.pd()
    for j in range(4):
        t.fd(length)
        t.seth(90*(j+1))
t.done()




sumtime = 0
percls = []
ts = {}
with open('out.txt', 'r') as f:
    for i in f:
        i = i.strip().split(',')
        ts[i[0]] = i[2]
        sumtime += eval(i[1])
print('the total execute time is ', sumtime)
tns = list(ts.items())
tns.sort(key=lambda x: x[1], reverse=True)
for i in range(3):
    print('the top {} percentage time is {}, spent in "{}" operation'.format(i, tns[i][1], tns[i][0]))


6



f = open("八十天环游地球.txt")
fo = open("八十天环游地球-章节.txt","w")
txt = f.readlines()
for line in txt:
    line = line.strip()
    if line[0]=="第" and line[2]=="章":
        fo.write(line+"\n")
fo.close()
f.close()


import jieba
f = open("八十天环游地球.txt")
datas = f.readlines()
l = []
for i in range(len(datas)):
    if datas[i][0] == "第" and datas[i][2] == "章":
        l.append(i)   # 每章节所在索引
    # line = datas[i].split(' ')
    # if datas[i][0] == "第" and "章" in line[0]:
    #     l.append(i)
for i in range(len(l)):
    if i != len(l) - 1:   # 最后一章节
        data = ''.join(datas[l[i]:l[i + 1]])
    else:
        data = ''.join(datas[l[i]:])
    s = data.split()[0]   # 第几章
    words = jieba.lcut(data)
    d = {}
    for y in words:
        if len(y) < 2:
            continue
        d[y] = d.get(y, 0) + 1
    lis = list(d.items())
    lis.sort(key=lambda x: x[1], reverse=True)
    print(s, lis[0][0], lis[0][1])
f.close()


新增1


1




s=input()
print("{:=>25,}".format(eval(s)))


2




s=input()
print(s[::-1])
print(len(s))


3




a, b, c = [int(x) for x in input().split(',')]
ls = []
for i in range(c):
    ls.append(a + (i * b))
print(ls)


4




import turtle
turtle.pensize(2)
d=0
for i in range(1, 13):
    turtle.fd(40)
    d += 30
    turtle.seth(d)


5




ls = [111, 222, 333, 444, 555, 666, 777, 888, 999]
lt = [999, 777, 555, 333, 111, 888, 666, 444, 222]
s = 0
for i in range(len(ls)):
    s += ls[i]*lt[i]
print(s)


6



L = []
fo = open("score.txt", "r")
fi = open("candidate0.txt", "w")
lines = fo.readlines()
for line in lines:
    line = line.strip()
    student = line.split(' ')
    sum = 0
    for i in range(1, 11):
        sum += int(student[-i])
    student.append(str(sum))
    L.append(student)
L.sort(key=lambda x: x[-1], reverse=True)
for i in range(10):
    fi.write(' '.join(L[i][:-1]) + '\n')
fo.close()
fi.close()


fi = open("candidate0.txt", "r")
fo = open("candidate.txt", 'w')
L = []
lines = fi.readlines()
for line in lines:
    line = line.strip()
    student = line.split(' ')
    for i in student[2:]:
        if int(i) < 60:
            break
    else:
        L.append(student[:2])
for i in L:
    fo.write(' '.join(i) + '\n')
fi.close()
fo.close()


新增2


1




n = eval(input("请输入正整数:"))
print("{:*>15}".format(n))


2




a = [3,6,9]
b =  eval(input()) #例如:[1,2,3]
c = []
for i in range(3):
    c.append(a[i]+b[i])
print(c)


3




import random
random.seed(0)
s = 0
for i in range(5):
    n = random.randint(1,97)  # 产生随机数
    s = s + n**2
print(s)


4



import turtle
turtle.pensize(2)
d = 0
for i in range(1, 9):
    turtle.fd(100)
    d += 45
    turtle.seth(d)


5



f=open("name.txt")
names=f.readlines()
f.close()
f=open("vote.txt")
votes=f.readlines()
f.close()
f=open("vote1.txt","w")
D={}
NUM=0
for vote in votes:
    num = len(vote.split())
    if num==1 and vote in names:
        D[vote[:-1]]=D.get(vote[:-1], 0)+1
        NUM+=1
    else:
        f.write(vote)
f.close()        
l=list(D.items())
l.sort(key=lambda s:s[1],reverse=True)
name=l[0][0]
score=l[0][1]
print("有效票数为:{} 当选村长村民为:{},票数为:{}".format(NUM,name,score))


6



import jieba
f = open('data.txt','r')   
lines = f.readlines()
f.close()
f = open('out.txt','w')    
for line in lines:     
    line=line.strip(' ')              #删除每行首尾可能出现的空格
    wordList = jieba.lcut(line)         #用结巴分词,对每行内容进行分词
    f.writelines('\n'.join(wordList))  #将分词结果存到文件out.txt中
f.close()


import jieba
f = open('out.txt','r')    #以读的方式打开文件
words = f.readlines()
f.close()
D={}
for w in words:        #词频统计
    D[w[:-1]]=D.get(w[:-1], 0) + 1
print("曹操出现次数为:{}  ".format(D["曹操"]))


新增3


1




ls = eval(input())
s = ""
for item in ls:
    if type(item) == type("香山"):
        s += item
print(s)


2



import random
random.seed(25)
n = random.randint(1,100)
for m in range(1,7):
    x = eval(input("请输入猜测数字:"))
    if x == n:
        print("恭喜你,猜对了!")
        break
    elif  x>n:
        print("大了,再试试")
    else:
        print("小了,再试试")
    if m==6:
        print("谢谢!请休息后再猜")


3




def f(n):
    s = 0
    if n%2==1:
        for i in range(1, n+1, 2):
            s += 1/i
    else:
        for i in range(2, n+1, 2):
            s += 1/i
    return s
n = int(input())
print('{:.2f}'.format(f(n)))


4




import turtle as t
color = ['red','green','blue']
rs = [10,30,60]
for i in range(3):
    t.penup()
    t.goto(0, -rs[i])
    t.pd()
    t.pencolor(color[i])
    t.circle(rs[i])
t.done()


5




import jieba
s = input("请输入一段中文文本,句子之间以逗号或句号分隔:")
slist = jieba.lcut(s)
m = 0
for i in slist:
    if i in ",。":
        continue
    m += 1
    print(i, end='/')
print("\n中文词语数是:{}\n".format(m))
ss = ''
for i in s:
    if i in ',。':
        print('{:^20}'.format(ss))
        ss = ''
        continue
    ss += i


6



fi = open("data.txt",'r')
fo = open("studs.txt",'w')
datas = fi.readlines()
for data in datas:
    data1 = data.strip().split(':')
    data2 = data1[1].split(',')
    name = data1[0]
    score = data2[1]
    fo.write(name+":"+score+"\n")
fi.close()
fo.close()


fi = open("data.txt",'r')
datas = fi.readlines()
d = {}
for data in datas:
    data1 = data.strip().split(':')
    data2 = data1[1].split(',')
    name = data1[0]
    score = data2[1]
    d[name] = score
lst = list(d.items())
lst.sort(key=lambda x:x[1], reverse=True)
print(lst[0][0]+":"+lst[0][1])
fi.close()


fi = open("data.txt", 'r')
datas = fi.readlines()
d = {}
for data in datas:
    data1 = data.strip().split(':')[1]
    banji, score = data1.split(',')
    d[banji] = d.get(banji, []) + [int(score)]
for i in d.items():
    print(i[0] + ":" + "{:.2f}".format(sum(i[1]) / len(i[1])))
fi.close()


目录
相关文章
|
1月前
|
人工智能 数据可视化 数据挖掘
探索Python编程:从基础到高级
在这篇文章中,我们将一起深入探索Python编程的世界。无论你是初学者还是有经验的程序员,都可以从中获得新的知识和技能。我们将从Python的基础语法开始,然后逐步过渡到更复杂的主题,如面向对象编程、异常处理和模块使用。最后,我们将通过一些实际的代码示例,来展示如何应用这些知识解决实际问题。让我们一起开启Python编程的旅程吧!
|
1月前
|
存储 数据采集 人工智能
Python编程入门:从零基础到实战应用
本文是一篇面向初学者的Python编程教程,旨在帮助读者从零开始学习Python编程语言。文章首先介绍了Python的基本概念和特点,然后通过一个简单的例子展示了如何编写Python代码。接下来,文章详细介绍了Python的数据类型、变量、运算符、控制结构、函数等基本语法知识。最后,文章通过一个实战项目——制作一个简单的计算器程序,帮助读者巩固所学知识并提高编程技能。
|
21天前
|
Unix Linux 程序员
[oeasy]python053_学编程为什么从hello_world_开始
视频介绍了“Hello World”程序的由来及其在编程中的重要性。从贝尔实验室诞生的Unix系统和C语言说起,讲述了“Hello World”作为经典示例的起源和流传过程。文章还探讨了C语言对其他编程语言的影响,以及它在系统编程中的地位。最后总结了“Hello World”、print、小括号和双引号等编程概念的来源。
105 80
|
10天前
|
Python
[oeasy]python055_python编程_容易出现的问题_函数名的重新赋值_print_int
本文介绍了Python编程中容易出现的问题,特别是函数名、类名和模块名的重新赋值。通过具体示例展示了将内建函数(如`print`、`int`、`max`)或模块名(如`os`)重新赋值为其他类型后,会导致原有功能失效。例如,将`print`赋值为整数后,无法再用其输出内容;将`int`赋值为整数后,无法再进行类型转换。重新赋值后,这些名称失去了原有的功能,可能导致程序错误。总结指出,已有的函数名、类名和模块名不适合覆盖赋新值,否则会失去原有功能。如果需要使用类似的变量名,建议采用其他命名方式以避免冲突。
30 14
|
20天前
|
分布式计算 大数据 数据处理
技术评测:MaxCompute MaxFrame——阿里云自研分布式计算框架的Python编程接口
随着大数据和人工智能技术的发展,数据处理的需求日益增长。阿里云推出的MaxCompute MaxFrame(简称“MaxFrame”)是一个专为Python开发者设计的分布式计算框架,它不仅支持Python编程接口,还能直接利用MaxCompute的云原生大数据计算资源和服务。本文将通过一系列最佳实践测评,探讨MaxFrame在分布式Pandas处理以及大语言模型数据处理场景中的表现,并分析其在实际工作中的应用潜力。
57 2
|
1月前
|
小程序 开发者 Python
探索Python编程:从基础到实战
本文将引导你走进Python编程的世界,从基础语法开始,逐步深入到实战项目。我们将一起探讨如何在编程中发挥创意,解决问题,并分享一些实用的技巧和心得。无论你是编程新手还是有一定经验的开发者,这篇文章都将为你提供有价值的参考。让我们一起开启Python编程的探索之旅吧!
48 10
|
1月前
|
机器学习/深度学习 人工智能 数据挖掘
探索Python编程的奥秘
在数字世界的海洋中,Python如同一艘灵活的帆船,引领着无数探险者穿梭于数据的波涛之中。本文将带你领略Python编程的魅力,从基础语法到实际应用,一步步揭开Python的神秘面纱。
45 12
|
1月前
|
IDE 程序员 开发工具
Python编程入门:打造你的第一个程序
迈出编程的第一步,就像在未知的海洋中航行。本文是你启航的指南针,带你了解Python这门语言的魅力所在,并手把手教你构建第一个属于自己的程序。从安装环境到编写代码,我们将一步步走过这段旅程。准备好了吗?让我们开始吧!
|
1月前
|
关系型数据库 开发者 Python
Python编程中的面向对象设计原则####
在本文中,我们将探讨Python编程中的面向对象设计原则。面向对象编程(OOP)是一种通过使用“对象”和“类”的概念来组织代码的方法。我们将介绍SOLID原则,包括单一职责原则、开放/封闭原则、里氏替换原则、接口隔离原则和依赖倒置原则。这些原则有助于提高代码的可读性、可维护性和可扩展性。 ####
|
1月前
|
人工智能 数据挖掘 开发者
探索Python编程之美:从基础到进阶
本文是一篇深入浅出的Python编程指南,旨在帮助初学者理解Python编程的核心概念,并引导他们逐步掌握更高级的技术。文章不仅涵盖了Python的基础语法,还深入探讨了面向对象编程、函数式编程等高级主题。通过丰富的代码示例和实践项目,读者将能够巩固所学知识,提升编程技能。无论你是编程新手还是有一定经验的开发者,这篇文章都将为你提供有价值的参考和启示。让我们一起踏上Python编程的美妙旅程吧!