实验题目:
1、编写程序,查找一个字符串中最长的数字子串。
import sys
def solve():
for line in sys.stdin:
str=list(line)
count=0
length=0
temp=[]
dig=[]
for i in range(str.__len__()):
if(str[i]>='0' and str[i]<='9'):
count+=1
temp.append((str[i]))
else:
if count>length:
length=count
count=0
dig=temp.copy()
temp=[]
else:
temp=[]
count=0
result=''.join((dig))
print("%s,%d" %(result,length))
if __name__ == "__main__":
solve()
2.接收一个字符串,分别统计大写字母、小写字母、数字、其他字符的个数。
intcount=[]
upstrcount=[]
lowstrcount=[]
othercount=[]
def number(a):
for i in a:
if i.isdigit():
intcount.append(i)
elif i.isupper():
upstrcount.append(i)
elif i.islower():
lowstrcount.append(i)
else:
othercount.append(i)
return intcount,upstrcount,lowstrcount,othercount
a=input('请输入一个字符串:')
a,b,c,d=number(a)
print('大写字母的个数:{}'.format(len(b)))
print('小写字母的个数:{}'.format(len(c)))
print('数字的个数:{}'.format(len(a)))
print('其他数字的个数:{}'.format(len(d)))
a=tuple(a)
b=tuple(b)
c=tuple(c)
d=tuple(d)
print(a,b,c,d)
3.打印对顶菱形
for i in range(1,7):
print("{0: ^20}".format("*"*(2*i-1)))
for i in range(7,1,-1):
print("{0: ^20}".format("*"*(2*i-1)))
4.给定任意字符串,查找其中每个字符的最后一次出现,并按每个字符最后一次出现的先后顺序依次存入列表。例如对于字符串’abcda’的处理结果为[‘b’, ‘c’, ‘d’, ‘a’],而字符串’abcbda’的处理结果为[‘c’, ‘b’, ‘d’, ‘a’]。
dict1 = {'a':0, 'b':0, 'c':0, 'd':0, 'e':0, 'f':0, 'g':0,
'h':0, 'i':0, 'j':0, 'k':0, 'l':0, 'm':0, 'n':0,
'o':0, 'p':0, 'q':0, 'r':0, 's':0, 't':0, 'u':0,
'v':0, 'w':0, 'x':0, 'y':0, 'z':0}
num = 0 #用于指示字符串的字符下标
def function(a, dict1, num):
for i in a:
num += 1
if i in dict1:
dict1[i] = num
return dict1
a = str(input())
function(a, dict1, num)
for x in dict1:
if dict1[x] != 0:
print("char:{}, last site:{}".format(x, dict1[x]))
参数:
正则表达式:
实验五:面向对象
1.时间类:
class Time:
def __init__(self,hours,minutes,seconds):
self.setHours(hours)
self.setMinutes(minutes)
self.setSeconds(seconds)
def setHours(self,h):
self.__Hours=h
def setMinutes(self,m):
self.__Minutes=m
def setSeconds(self,s):
self.__Seconds=s
def PintTime(self):
print(f"当前时间为:{self.__Hours}:{self.__Minutes}:{self.__Seconds}")
# 9:35:59
def AddOneSec(self):
if(self.__Seconds==59):
self.__Seconds=0
if(self.__Minutes==59):
self.__Minutes=0
if(self.__Hours==24):
self.__Hours=1
else:
self.__Seconds+=1
if __name__=="__main__":
time=Time(8,40,38)
time.PintTime()
print("时间自增")
time.AddOneSec()
time.PintTime()
time=Time(24,59,59)
time.PintTime()
print("时间自增")
time.AddOneSec()
time.PintTime()
2.继承:
class Person(object):
def __init__(self, name='', age=20, sex='man'):
self.setName(name)
self.setAge(age)
self.setSex(sex)
def setName(self, name):
self.__name = name
def setAge(self, age):
self.__age = age
def setSex(self, sex):
if sex != 'man' and sex != 'woman':
print('sex must be "man" or "woman"')
return
self.__sex = sex
def getname(self):
return self.__name
def getage(self):
return self.__age
# 自定义内置比较特殊方法
def __eq__(self, other):
if self.__age == other.__age:
return True
else:
return False
def __str__(self):
msg = f"我的姓名是{self.__name},我的年龄是{self.__age}"
return msg
class Teacher(Person):
def __init__(self, Occupation="教师", name='', age=10, sex='man', department='Math'):
super(Teacher, self).__init__(name, age, sex)
## or, use another method like below:
# Person.__init__(self, name, age, sex)
self.setDepartment(department)
self.setOccupation(Occupation)
def setDepartment(self, department):
self.__department = department
def setOccupation(self, Occupation):
self.__Occupation = Occupation
def __str__(self):
msg = f"我的姓名是{self.getage()},我的年龄是{self.getage()},我的职业是{self.__Occupation},我教的科目是{self.__department}"
return msg
class Student(Person):
def __init__(self, Occupation, name='', age=20, sex='man', grade=1):
# 初始化基类的数据成员
# 1.super调基类的构造函数
super(Student, self).__init__(name, age, sex)
# 2.基类名.方法名
# Person.__init__(self,name,age,sex)
# 初始化子类属性
self.setgrade(grade)
self.setOccupation(Occupation)
def setgrade(self, grade):
# if type(department)!=str:
# raise Exception("部门必须是str")
self.__grade = grade
def setOccupation(self, Occupation):
self.__Occupation = Occupation
# 重写
def __str__(self):
msg = f"我的姓名是{self.getname()},我的年龄是{self.getage()},我的职业是{self.__Occupation},我的年级是{self.__grade}"
return msg
if __name__ == '__main__':
# 创建基类
print("创建基类Person")
person = Person("人类", 20, "woman")
# 使用print方法时 会嗲用重写的str方法的内容
print(person)
print("*" * 30, "创建教师", "*" * 30)
# 创建子类
teacher1 = Teacher("教师", "阿强", "20", "man", "文学")
print(teacher1)
teacher2 = Teacher("教师", "阿东", "21", "man", "电焊")
print(teacher1)
if teacher1 == teacher2:
print(f"{teacher1.getname()}与{teacher2.getname()}年龄相等")
else:
print(f"{teacher1.getname()}与{teacher2.getname()}年龄不相等")
print("*" * 30, "创建学生", "*" * 30)
student1 = Teacher("学生", "阿丽", "19", "woman", "2年级")
print(student1)
文件操作:
其中random.sample方法:
利用zip函数将两个list组成字典
文件合并代码 :
import random
def WriteScore(name,kemu):
with open(name, 'w+') as f:
total="姓名"+" "+kemu+'\n'
f.write(total)
name_list=['张三','王五','李四','阿强','阿东','阿龙','阿丽']
score=random.sample(range(0,101),7)
score_list=map(str,score)#转字符串
#转成字典
dist= dict(zip(name_list, score_list))
#遍历写入
list_ = dist.items()
for k, v in list_:
str_=k+v+'\n'
f.write(k+' '+v+'\n')
"""文件合并"""
def hebing_file(f1,f2,f3):
score=[]
f1_name=[]
f2_name=[]
f1_sc=[]
f2_sc=[]
f3_name=[]
s = ""
with open(f1, 'r') as file1:
file1_=file1.readlines()
for i in file1_:
temp_list =i.split()
# 将txt文件中的第一行 也就是file_list1 列表的第一项 用split方法操作 以空格为分隔符 分成两部分继续放到temp_list列表里
f1_name.append(str(temp_list[0])) # 包含中文 选gbk
f1_sc.append(str(temp_list[1]))
with open(f2, 'r') as file2:
file2_=file2.readlines()
for i in file2_:
temp_list =i.split()
# 将txt文件中的第一行 也就是file_list1 列表的第一项 用split方法操作 以空格为分隔符 分成两部分继续放到temp_list列表里
f2_name.append(str(temp_list[0]))
f2_sc.append(str(temp_list[1]))
for i in range(len(f1_name)):
s = ''
if f1_name[i] in f2_name:
j =f2_name.index(f1_name[i]) # 列表index方法 查找括号内对象 返回值为索引位置
s = '\t'.join([f1_name[i], f1_sc[i],f2_sc[j]])
# 字符串join方法连接三个属性,之间以(\t 制表位)隔开
s += '\n'
else:
s = '\t'.join([f1_name[i], f1_sc[i], str("--------------")])
s += '\n'
f3_name.append(s)
# 选择file_list1中的名称与file_list2中的名称不相同的
for i in range(len(f2_name)):
s = ''
if f2_name[i] not in f1_name:
s = '\t'.join([f2_name[i], str('--------------'), f2_sc[i]])
s += '\n'
f3_name.append(s)
# 合并后的文件
with open(f3, 'w') as file3:
file3.writelines(f3_name)
if __name__=="__main__":
WriteScore("math.txt","数学")
WriteScore("chinese.txt","语文")
hebing_file("chinese.txt","math.txt","score.txt")
list切片返回一个列表