某农带专业Python实验二
公式计算
题目描述:编写三个函数fz(n), fm(n), sum_(n)分别计算下列公式的分子和,分母积以及公式总和值。
\[s=1+\frac{1+2}{1 \times 2}+\frac{1+2+3}{1 \times 2 \times 3}+\cdots+\frac{1+2+3+\cdots+n}{1 \times 2 \times 3 \times \ldots \times n} \]提示:采用函数嵌套实现
代码实现:
# -*- coding: utf-8 -*-
"""
PROJECT_NAME: pythonProject_ lesson
FILE_NAME: fraction
AUTHOR: welt
E_MAIL: [email protected]
DATE: 2022/11/10
分子分母的计算
"""
def fz(n):
return sum(range(1, n+1))
def fm(n):
m = 1
for i in range(1, n+1):
m *= i
return m
def sum_(n):
s = 0
for i in range(1, n+1):
s += fz(i)/fm(i)
return s
if __name__ == '__main__':
number = input('请输入需要计算的数字: ')
number = int(number)
print("运算结果为: ", sum_(number))
阶乘计算
题目描述:编写一个函数fac(n)求给定整数的阶乘,调用此函数实现以下公式。
\[C_n^m=\frac{n !}{m !(n-m) !} \]提示:采用递归实现
代码实现:
# -*- coding: utf-8 -*-
"""
PROJECT_NAME: pythonProject_ lesson
FILE_NAME: factorial
AUTHOR: welt
E_MAIL: [email protected]
DATE: 2022/11/10
阶乘
"""
def fac(n):
if n == 0 or n == 1:
return 1
else:
return n * fac(n - 1)
if __name__ == '__main__':
m = input("请输入m:")
n = input("请输入n:")
n, m = int(n), int(m)
result = fac(n) / (fac(m) * fac(n - m))
print("结果为:", result)
回文数判断
题目描述:编写一个函数isHui(n),用以实现对正整数n判断是否是回文数。
提示:回文数定义:是指顺读与倒读数字相同的正整数。如12321。说明如下:
(1)简单粗暴,直接反向,相等为回文,不相等则不是回文
代码实现:
# -*- coding: utf-8 -*-
"""
PROJECT_NAME: pythonProject_ lesson
FILE_NAME: palindrome
AUTHOR: welt
E_MAIL: [email protected]
DATE: 2022/11/10
判断是否为回文数
"""
def isHui(a):
b = a[::-1] # 倒序输出
if a == b: # 判断是否相等
print('{} 是回文数'.format(a)) # format方法输出
else:
print('{} 不是回文数'.format(a)) # format方法输出
if __name__ == '__main__':
judge_number = input('输入:') # 输入字符串
isHui(judge_number)
找最长单词
题目描述:编写一个函数maxWord(s),用以找出已知字符串s中的最长单词。
提示:输入“I am a student and my name is wpf!”,输出“student”。相关说明如下:
(1)使用split方法,将一个长字符串变为一个列表
(2)取出第一个单词为当前单词,遍历列表
(3)获取最长单词
# -*- coding: utf-8 -*-
"""
PROJECT_NAME: pythonProject_ lesson
FILE_NAME: maxwords
AUTHOR: welt
E_MAIL: [email protected]
DATE: 2022/11/10
"""
def maxWord(s):
words = s.split()
longest = words[0]
for word in words:
if len(word) > len(longest):
longest = word
print(longest)
if __name__ == '__main__':
string = "I am a student and my name is wpf!"
maxWord(string)
类的定义
题目描述:定义一个dog类,包含name、age、weight等属性,设计一个构造函数对这些属性记性初始化,然后实现并测试这个类。
代码实现:
# -*- coding: utf-8 -*-
"""
PROJECT_NAME: pythonProject_ lesson
FILE_NAME: dogclass
AUTHOR: welt
E_MAIL: [email protected]
DATE: 2022/11/10
"""
class Dog():
def __init__(self, inputname, inputage, inputweight):
self.name = inputname
self.age = inputage
self.weight = inputweight
if __name__ == '__main__':
cutedog = Dog("lxl", "8", "20")
print(cutedog.name)
print(cutedog.age)
print(cutedog.weight)
类的单继承
题目描述:定义一个 person基类,包含公有属性:姓名name、年龄age,具有speak()公有方法;从person类中派生出一个teacher子类,该类新增私有属性:专业profession、职称title、主讲课程course,并定义重写基类speak( )方法。
提示:实例测试
wpf = teacher('wpf', '42', 'computer science and technology', 'associate professor', 'Python programming desiging')
wpf.speak()
结果输出:
my name is wpf, I am 42 years old, And my profession is computer science and technology, my title is associate professor,my master course is Python programming desiging thank you!
代码实现:
# -*- coding: utf-8 -*-
"""
PROJECT_NAME: pythonProject_ lesson
FILE_NAME: personclasss
AUTHOR: welt
E_MAIL: [email protected]
DATE: 2022/11/10
"""
class person():
def __init__(self, inputname, inputage):
self.name = inputname
self.age = inputage
def speak(self):
print("hello!")
class teacher(person):
def __init__(self, name, age, profession, title, course):
super().__init__(name, age)
self.profession = profession
self.title = title
self.course = course
def speak(self):
print('my name is {0}, I am {1} years old, And my profession is {2}, my title is {3},my master course is {4} '
'thank you!'.format(self.name, self.age, self.profession, self.title, self.course))
if __name__ == '__main__':
wpf = teacher('wpf', '42', 'computer science and technology', 'associate professor', 'Python programming desiging')
wpf.speak()
类的多继承
题目描述:定义一个student基类,包含公有属性:学号sid、班级class_,具有study()公有方法;再定义一个teacher基类,包含公有属性:工号tid、学院dept,具有teach()公有方法;然后从student和teacher两个基类公共派生出一个doctor子类,该类新增公有属性:姓名name、年龄age,具有introduce()公有方法,不需要重写两个基类方法。
提示:实例测试
d1 = Doctor('2011038', 'Agricultural machinery engineering', '2001020', ' college of imformatics', 'wpf', 34)
d1.introduce()
d1.study()
d1.teach()
结果输出:
My name is wpf, I am 34 years old.
MY student's id is 2011038, I major in Agricultural machinery engineering.
And my teacher's id is 2001020 ,I am in college of imformatics.
代码实现:
# -*- coding: utf-8 -*-
"""
PROJECT_NAME: pythonProject_ lesson
FILE_NAME: studentclass
AUTHOR: welt
E_MAIL: [email protected]
DATE: 2022/11/10
"""
class Student():
def __init__(self, sid, class_):
self.sid = sid
self.class_ = class_
def study(self):
print("MY student's id is {}, I major in {}.".format(self.sid, self.class_))
class Teacher():
def __init__(self, tid, dept):
self.tid = tid
self.dept = dept
def teach(self):
print("And my teacher's id is {} ,I am in {}.".format(self.tid, self.dept))
class Doctor(Student, Teacher):
def __init__(self, sid, class_, tid, dept, name, age):
self.sid = sid
self.class_ = class_
self.tid = tid
self.dept = dept
self.name = name
self.age = age
def introduce(self):
print('My name is {}, I am {} years old.'.format(self.name, self.age))
if __name__ == '__main__':
d1 = Doctor('2011038', 'Agricultural machinery engineering', '2001020', ' college of imformatics', 'wpf', 34)
d1.introduce()
d1.study()
d1.teach()
类的运算符重载
题目描述:定义一个三维向量类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)实例测试:
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())
结果输出:
Vector3(8,10,12)
Vector3(-2,-2,-2)
Vector3(9,12,15)
Vector3(2.5,3.0,3.5)
7.0710678118654755
代码实现:
# -*- coding: utf-8 -*-
"""
PROJECT_NAME: pythonProject_ lesson
FILE_NAME: vectorclass
AUTHOR: welt
E_MAIL: [email protected]
DATE: 2022/11/10
"""
import math
class Vector3():
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __add__(self, anotherPoint):
return Vector3(self.x + anotherPoint.x, self.y + anotherPoint.y, self.z + anotherPoint.z)
def __sub__(self, anotherPoint):
return Vector3(self.x - anotherPoint.x, self.y - anotherPoint.y, self.z - anotherPoint.z)
def __mul__(self, n):
return Vector3(self.x * n, self.y * n, self.z * n)
def __truediv__(self, n):
return Vector3(self.x / n, self.y / n, self.z / n)
def __str__(self):
return f"Vector3({self.x},{self.y},{self.z})"
def length(self):
return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z)
if __name__ == '__main__':
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())
标签:__,函数,NAME,Python,self,print,def,name
From: https://www.cnblogs.com/tangjielin/p/16880637.html