Python語言程式設計實驗(2)—— Python函式與類
實驗1:公式計算
題目描述:
編寫三個函式fz(n), fm(n), sum_(n)分別計算下列公式的分子和,分母積以及公式總和值。
提示:採用函式巢狀實現
def fz(n): #計算分子部分
s=0.0
for i in range(n):
s+=i+1
return s
def fm(n): #計算分母部分
s=1.0
for i in range(n):
s *=i+1
return s
def sum_(n): #計算公式的值
s=0.0
for i in range(n):
s+=fz(i+1)/fm(i+1)
return s
n=int(input("輸入要計算的項數:"))
print(sum_(n))
實驗2:階乘計算
題目描述:
編寫一個函式fac(n )求給定整數的階乘,呼叫此函式實現以下公式。
提示:採用遞迴實現
def fac(n):
if n==1:
return 1;
else:
return fac(n-1)*n
def fac1(n):
s=1.0
for i in range(n):
s*= i+1
return s
n=int(input("輸入要組合計算的下數:"))
m=int(input("輸入要組合計算的上數:"))
print("遞迴方法一的結果:" + str(fac(n)/(fac(m)*fac(n-m))))
print("普通方法二的結果:" + str(fac1(n)/(fac1(m)*fac1(n-m))))
實驗3:迴文數判斷
題目描述:
編寫一個函式isHui(n),用以實現對正整數n判斷是否是迴文數。
提示:迴文數定義:是指順讀與倒讀數字相同的正整數。如12321。說明如下:
(1)求字串長度函式len(s)
(2)當前位置為i,則其對稱位置為j=len(s)-1-i
(3)切片方法取出字元判斷是否相對:s[i:i+1]==s[j:j+1]
def isHui(s):
f=True
n=len(s)
for i in range(n):
j=n-1-i #j為i的對稱位置
if s[i:i+1]!=s[j:j+1]: #當前位置i與對稱位置j
f=False
break
return f
n=input("輸入要組合計算的下數:")
if isHui(n):
print(n + "是迴文數!")
else:
print(n + "不是迴文數!")
實驗4:找最長單詞
題目描述:
編寫一個函式maxWord(s),用以找出已知字串s中的最長單詞。
提示:輸入“I am a student and my name is wpf!”,輸出“student”。相關說明如下:
(1)查詢空格函式i=s.find(’ '),通過while i>0迴圈查詢
(2)取出當前單詞:tempword=s[ :i]
(3)剔除單詞,重新賦值句子:s=s[i+1:]
def maxWord(s):
maxword=''
tempword=''
n=len(s)
i=s.find(' ') #查詢空格函式
s=s+' '
while i>0:
tempword=s[:i] #取出當前分割單詞
if len(maxword)<len(tempword):
maxword=tempword
s=s[i+1:] #剔除判斷後單詞,重新修改句子
i=s.find(' ')
return maxword
s=input("輸入英文句子:")
print(maxWord(s))
實驗5:類的定義
題目描述:
定義一個dog類,包含name、age、weight等屬性,設計一個建構函式對這些屬性記性初始化,然後實現並測試這個類。
class dog:
name=''
age=0
weight=0
def __init__(self,n,a,w):
self.name=n
self.age=0
self.weight=0
def run():
print("go fast!")
def bark():
print("woof...!")
def eat():
print("yummy...!")
#案例測試
d1=dog("Tom",2,28)
dog.bark()
dog.run()
dog.eat()
實驗6:類的單繼承
題目描述:
定義一個 person基類,包含公有屬性:姓名name、年齡age,具有speak()公有方法;從person類中派生出一個teacher子類,該類新增私有屬性:專業profession、職稱title、主講課程course,並定義重寫基類speak( )方法。
提示:例項測試
結果輸出:
class person: #基類定義
name='' #姓名
age=0 #年齡
def __init__(self,n,a):#定義構造方法
self.name=n
self.age=a
def speak(self):#定義類本身的方法
print("my name is %s,I am %d years old."%(self.name,self.age))
class teacher(person): #派生類定義
__profession='' #專業
__title='' #職稱
__course='' #主講課程
def __init__(self,n,a,p,t,c): #定義子類的建構函式
person.__init__(self,n,a) #呼叫父類的建構函式
self.__profession=p
self.__title=t
self.__course=c
def speak(self): #重寫父類的方法
print("my name is %s, I am %d years old,\nAnd my profession is %s,\nmy title is %s,\nmy master course is %s.\nthank you!"%(self.name,self.age,self.__profession,self.__title,self.__course))
#例項測試
s=teacher('wpf',42,'computer science and technology','associate professor','Python programming desiging')
s.speak()
實驗7:類的多繼承
題目描述:
定義一個student基類,包含公有屬性:學號sid、班級class_,具有study()公有方法;再定義一個teacher基類,包含公有屬性:工號tid、學院dept,具有teach()公有方法;然後從student和teacher兩個基類公共派生出一個doctor子類,該類新增公有屬性:姓名name、年齡age,具有introduce()公有方法,不需要重寫兩個基類方法。
提示:例項測試
結果輸出:
class student: #基類1定義
sid='' #學號
class_='' #班級
def __init__(self,s,c):
self.sid=s
self.class_=c
def study(self):
print("My student's id is %s,\nI major in %s."%(self.sid,self.class_))
class teacher: #基類2定義
tid='' #工號
dept='' #院系
def __init__(self,t,d):
self.tid=t
self.dept=d
def teach(self):
print("And my teacher's id is %s,\nI am in %s."%(self.tid,self.dept))
class doctor(student,teacher): #派生類3多重繼承
name=''
age=0
def __init__(self,s,c,t,d,n,a):
student.__init__(self,s,c) #基類1建構函式
teacher.__init__(self,t,d) #基類2建構函式
self.name=n
self.age=a
def introduce(self):
print("My name is %s, I am %d years old."%(self.name,self.age))
#例項測試
d1=doctor('2011038','Agricultural machinery engineering','2001020','college of imformatics','wpf',34)
d1.introduce()
d1.study()
d1.teach()
實驗8:類的運算子過載
題目描述:
定義一個三維向量類Vector3,並定義相應的特殊方法實現兩個該類物件之間的加、減運算(要求支援運算子+、-),實現該類物件與標量的乘、除運算(要求支援運算子*、/),以及向量長度的計算(要求使用屬性實現,其中向量長度是向量所有分量平方和的平方根)。
提示:
通過類的專有方法__add__()、sub()、mul()、__truediv()分別實現+、-、*、/運算子過載;通過類的專有方法__str()查看向量,格式化顯示向量座標分量;通過自定義方法length(self)計算向量長度,並@property方法將向量長度設定為屬性值。具體做法如下:
(1)定義向量構造方法:init(self, x, y, z),實現向量初始化Vector3(x, y, z)
(2)定義向量與另一個向量的加法+運算:add(self, anotherPoint)
(3)定義向量與另一個向量的加法-運算:sub(self, anotherPoint)
(4)定義向量與某一個標量的乘法*運算:mul(self, n)
(5)定義向量與某一個標量的除法/運算:truediv(self, n),注意:此處不是__div__
(6)定義向量檢視方法:str(self),格式化顯示向量座標分量
(7)定義向量長度計算方法:length(self),實現向量所有分量平方和的平方根。
(8)例項測試:
結果輸出:
class Vector3:
#構造方法,初始化,定義向量座標
def __init__(self,x,y,z):
self.__x=x
self.__y=y
self.__z=z
#加上一個向量,對應分量相加,返回新向量
def __add__(self,anotherPoint):
x=self.__x + anotherPoint.__x
y=self.__y + anotherPoint.__y
z=self.__z + anotherPoint.__z
return Vector3(x,y,z)
#減去一個向量,對應分量相減,返回新向量
def __sub__(self,anotherPoint):
x=self.__x - anotherPoint.__x
y=self.__y - anotherPoint.__y
z=self.__z - anotherPoint.__z
return Vector3(x,y,z)
#向量與一個數字相乘,各分量乘以同一個數字,返回新向量
def __mul__(self,n):
x,y,z=self.__x*n, self.__y*n, self.__z*n
return Vector3(x,y,z)
#向量與一個數字相除,各分量除以同一個數字,返回新向量
def __truediv__(self,n):
x,y,z=self.__x/n, self.__y/n, self.__z/n
return Vector3(x,y,z)
#查看向量,格式化顯示向量座標分量
def __str__(self):
return "Vector3({},{},{})".format(self.__x,self.__y,self.__z)
#計算向量長度設定為屬性,向量長度即所有分量平方和的平方根
@property
def length(self):
return (self.__x**2 + self.__y**2 + self.__z**2)**0.5
#例項測試
v1=Vector3(3,4,5)
v2=Vector3(5,6,7)
print(v1+v2)
print(v1-v2)
print(v1*3)
print(v2/2)
print(v1.length)