python課堂實驗(6)
阿新 • • 發佈:2022-05-13
第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()