Python实验三函数与文件操作

1)编写函数,传入一个由实数元素构成的列表,返回一个字典,字典内容为{‘max’:最大值,‘min’:最小值,‘ave’:平均值,‘std’:样本标准方差}。其中样本标准方差的计算公式为:

def fun(list):
	all=0
	ave=0
	max=0
	min=-1
	n=0
	for i in list:
		all+=i
		ave+=1
		if(min>i or min==-1):
			min=i
		if(max<i):
			max=i
	ave=all/ave
	for j in list:
		n+=1
		std=(i-ave)**2
	std=round((std/(n-1))**0.5,2)
	return {'最大值':max,'最小值':min,'平均值':ave,'样本标准方差':std}

list=[1,3,5,6]
print(fun(list))

2)输入一串字符作为密码,密码只能由数字与字母组成。编写一个函数judge(password),用来求出密码的强度level,根据输入,输出对应密码强度。密码强度判断准则如下(满足其中一条,密码强度增加一级):①有数字;②有大写字母;③有小写字母;④位数不少于8位。

def judge(password):
	all=0
	flag=0
	a=0
	b=0
	c=0
	d=0
	for i in password:
		all+=1
		if(i.isdigit() and a==0):
			flag+=1
			a=1
		if(i.islower() and b==0):
			flag+=1
			b=1
		if(i.isupper() and c==0):
			flag+=1
			c=1
		if(all>=8 and d==0):
			flag+=1
			d=1
	print(all)
	return	flag

password='123asdASD'
print(judge(password))

3)新建一个文本文件zen.txt,文件内容为“Python之禅”的部分内容,具体如下:
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
编写程序统计该文件内容的行数及单词的个数。

file=open("zen.txt","w+",encoding='utf-8')
file.write("Beautiful is better than ugly.\nExplicit is better than implicit."
 "\nSimple is better than complex.\nComplex is better than complicated.")
file.close()
file=open("zen.txt","r+",encoding='utf-8')
hang=0
word=0
for i in file.readlines():
	hang+=1
	ls=i.split(" ")
	word+=len(ls)
	print(i)
print(word)
print(hang)

4)新建一个文本文件score.csv,用来保存3名考生3门课程的成绩,内容如下:
考号,程序设计,高数,马哲
10153450101,72,96,88
10153450101,68,88,73
10153450101,95,64,65
以上各数据均使用英文逗号分隔。请编写程序读取该文件内容,并统计每门课程的平均分、最高分和最低分。

import csv
fileHeader=["考号","程序设计","高数","马哲"]
d1=[10153450101,72,96,88]
d2=[10153450101,68,88,73]
d3=[10153450101,95,64,65]
csvFile = open("score.csv", "w",encoding='utf-8-sig')
writer = csv.writer(csvFile)
r1=(d1[1]+d2[1]+d3[1])/3
print('程序设计 %.2f'%r1)
r2=(d1[2]+d2[2]+d3[2])/3
print('高数 %.2f'%r2)
r3=(d1[3]+d2[3]+d3[3])/3
print('马哲 %.2f'%r3)
d4=['平均分',r1,r2,r3]
# 写入的内容都是以列表的形式传入函数
writer.writerows([fileHeader,d1,d2,d3,d4])
csvFile.close()

物联沃分享整理
物联沃-IOTWORD物联网 » Python实验三函数与文件操作

发表评论