python课堂实验(6)
作者:互联网
第6次实验
1、计算1000以内的所有完数个数和
n = 0 for i in range(1,1001): s = 1 for j in range(2,i): if i%j == 0: s = s + j if s == i: n = n+i print('1000以内共有{}个完数'.format(n))
2、区间素数和
def lsPrime(n): for i in range(2,n-1): if n%i==0: return False return True m,n = eval(input('请输入整数m:')),eval (input('请输入整数n:')) c = 0 for i in range(m,n+1): if IsPrime(i): c = c+i print('范围在[{},{}的素数和为{}'.format(m,n,c))
3、
1)定义函数def f_write:用随机函数生成10行数据,每行数据个数3到8个不等,每个整数范围为[-50,50]。数据保存为data.txt
import random random.seed(1000) def f_write(): a = open("data.txt",'w') for i in range(10): s = random.randint(3,9) for j in range(s): a.write(str(random.randint(-50,50))) if j == s-1: a.wrte('\n') else: a.write(',') a.close
2)定义函数def f_read(),用read函数求文件data.txt中全部数字的最大值,并输出
def f_read() max1 = 0 a = open("data.txt",'r') for i in range(10): str = f.readline() num = str.split('') for j in num: if int(j)>max1: max1 = int(j) print('数字最大值',max1) f.close()
3)用readlines求每行数字和的最大值
def f_readlines(): f = open('data.txt','r') maxn=0 line = f.readlines() for str in line: num=str.split('') sum=0 for j in num: sum=sum+int(j) if maxn<sum: maxn=sum print("每行和最大值",maxn)
4、下载附件,每行有3个整数(有负数)。编写程序,读入所有数据,如果某行的三个整数能构成三角形则计算其面积,输出所有面积的最大值(保留两位小数)及三个边长的值。若三角形三边长分别为a,b,c,计算p=(a+b+c)/2,则该三角形的面积的平方=p*(p-a)*(p-b)*(p-c)。
f = open('整数.txt','r') count=0 a,b,c,max= 0,0,0.0 for line in f: line=line.replace('\n','') d=line.split(',') if len(d)==3: x=eval(d[0]) y=eval(d[1]) z=eval(d[2]) if x>0 and y>0 and z>0 and x+y>z and x+z>y and y+z>x: p=(x+y+z)/2 s=(p*(p-x)*(p-y)*(p-z))**0.5 if s>max: max=s a,b,c=x,y,z f.close()
5、
f=open("阶乘.txt","w") t=1 for i in range(1,101): t = t*i f.write('str(i)+"!="+str(t)+"\n") f.close()
标签:python,range,实验,str,课堂,txt,open,line,def 来源: https://www.cnblogs.com/lxhlxwly/p/16266036.html