11-1 新型计算器
**题目:**设计一个计算器,实现一个三维向量的加法,减法以及向量和标量的乘法和除法运算
提示:
1、定义类名为 VecCal,设计构造函数创建三维向量对象: def init(self, x=0,y=0,z=0) 用x,y,z指代三个维度的值
2、重写加法(+),减法(-),乘法(* )和整除除法(//)运算,实现向量的加减乘除
3、除法运算作异常处理,当输入标量数字是0时,除法结果为 (0,0,0)
加法示例:
def __add__(self, n): # 加法
result = VecCal() # 定义结果变量,也是一个三维向量,通过构造函数创建
result.X = self.X + n.X
result.Y = self.Y + n.Y
result.Z = self.Z + n.Z
return result # 返回 执行加法运算后的向量结果
输入格式:
第一行输入一个三维向量,逗号分隔,如:1,2,3
第二行输入另一个三维向量,逗号分隔:如:4,5,6
第三行输入一个数字, 如:3
输出格式:
(1, 2, 3) + (4, 5, 6) = (5, 7, 9)
(1, 2, 3) - (4, 5, 6) = (-3, -3, -3)
(1, 2, 3) * 3 = (3, 6, 9)
(1, 2, 3) / 3 = (0, 0, 1)
输入样例:
在这里给出一组输入。例如:
1,2,3
4,5,6
3
输出样例:
在这里给出相应的输出。例如:
(1, 2, 3) + (4, 5, 6) = (5, 7, 9)
(1, 2, 3) - (4, 5, 6) = (-3, -3, -3)
(1, 2, 3) * 3 = (3, 6, 9)
(1, 2, 3) / 3 = (0, 0, 1)
class VecCal(object):
def __init__(self,x=0,y=0,z=0):
self.X = x
self.Y = y
self.Z = z
def __add__(self,n):
result = VecCal()
result.X = self.X + n.X
result.Y = self.Y + n.Y
result.Z = self.Z + n.Z
return result
def __sub__(self,n):
result = VecCal()
result.X = self.X - n.X
result.Y = self.Y - n.Y
result.Z = self.Z - n.Z
return result
def __mul__(self,n):
result = VecCal()
result.X = self.X * n
result.Y = self.Y * n
result.Z = self.Z * n
return result
def __floordiv__(self,n):
result = VecCal()
result.X = self.X // n
result.Y = self.Y // n
result.Z = self.Z // n
return result
def __str__(self):
return '({0}, {1}, {2})'.format(self.X,self.Y,self.Z)
num1 = VecCal(*map(int,input().split(',')))
num2 = VecCal(*map(int,input().split(',')))
n=int(input())
print(num1,'+',num2,'=',num1+num2)
print(num1,'-',num2,'=',num1-num2)
print(num1,'*',n,'=',num1*n)
if n != 0:
print(num1,'/',n,'=',num1//n)
else :
print(num1,'/',n,'=','(0, 0, 0)')
11-2 优异生查询(类和对象)
题目: 编程实现查找优异生的功能——用户输入多个学生的成绩,输出总分最高的学生姓名和各科成绩
要求: 设计一个学生类(Student),包括属性有:姓名(name),数学成绩(mscore),语文成绩(cscore),英语成绩(escore);方法有:构造方法,计算总成绩方法,获得优异生姓名和所有成绩的方法
输入格式:
通过4行输入:
第一行输入多个学生姓名,以空格分隔
第二行输入多个数学成绩,以空格分隔
第三行输入多个语文成绩,以空格分隔
第四行输入多个英语成绩,以空格分隔
注意:学生姓名个数要和成绩个数保持一致
输出格式:
在一行中,输出总分最高的学生及其各科科目成绩,以空格分隔。
输入样例:
在这里给出一组输入。例如:
Jack Tom Jim
95 84 32
90 75 45
85 90 67
输出样例:
在这里给出相应的输出。例如:
Jack 95 90 85
class Student(object):
def __init__(self,name,mscore,cscore,escore):
self.name = name
self.mscore = mscore
self.cscore = cscore
self.escore = escore
self.s = mscore + cscore + escore
def func1(self):
return self.mscore + self.cscore + self. escore
def func2(stulist):
return max(stulist,key = lambda x:x.func1())
def __str__(self):
return '{0} {1} {2} {3}'.format(self.name,self.mscore,self.cscore,self.escore)
data = []
data.append(input().split())
for i in range(3):
data.append(list(map(int,input().split())))
lst = [Student(*[row[i] for row in data]) for i in range(len(data[0]))]
print(Student.func2(lst))
这篇博客介绍了Python编程中的两个实例:一是设计一个三维向量的新型计算器,实现加减乘除运算,包括处理除以0的情况;二是实现一个查找优异生的功能,通过类和对象的方法计算总分并输出最高分学生的信息。
&spm=1001.2101.3001.5002&articleId=103409028&d=1&t=3&u=949d49d69b17435b929f0b6b7584b72c)
8943

被折叠的 条评论
为什么被折叠?



