使用numpy python计算分数

wfsdck30  于 12个月前  发布在  Python
关注(0)|答案(1)|浏览(109)

Question on Grade Calculator using Python Numpy
试试上面的问题,如果你知道莫尔技术和方法,建议以一种简单的方式解决它。你也可以在GitHub上编辑我的代码

5lhxktic

5lhxktic1#

您的原始代码:

from numpy import *
a=array([[100,90,80,70,60,50,45],[90,80,70,60,50,40,30]])
L=["S", "A","B","C","D","E","F"]
n=int(input("Enter Marks Scored by Students: "))
for i in range(len(L)):
    if a[0][i]>n and a[1][i]<n:
        b=L[i]
print("Grade",b)

我对此有一些评论:

from numpy import *

这通常被认为是不好的做法,因为它将所有函数从numpy导入到您的命名空间中,这可能会导致问题并覆盖现有函数,特别是如果您开始在较大的项目中定义自己的函数。更好的做法是

import numpy as np
a = np.array([...])
if a[0][i]>n and a[1][i]<n:

这个条件是有缺陷的。例如,如果学生得分为90,则90既不小于90也不大于100,并且不会被分配等级。此外,最好的做法是在条件语句中预测边缘情况。例如,输入超出范围的分数20会导致NameError,因为未定义B。

NameError: name 'b' is not defined

我在下面提供了一个改进的片段,并评论了我的更改:

# Import the numpy library and give it an alias 'np' for easier referencing.
import numpy as np

# Create a 2D numpy array where the first row represents the upper bounds of grades and the second row represents the lower bounds.
a = np.array([[100, 90, 80, 70, 60, 50, 45], [90, 80, 70, 60, 50, 40, 30]])
L = ["S", "A", "B", "C", "D", "E", "F"]
n = int(input("Enter Marks Scored by Students: "))

# Create a mask (Boolean array) where each element is True if the student's score falls within the corresponding grade boundary.
grade_mask = (a[1] <= n) & (n < a[0])

# Find the index (position) of the grade boundary that the student's score falls into.
index = np.where(grade_mask)[0]

# If there's a match (i.e., the student's score falls within one of the grade boundaries), assign the corresponding grade label. Otherwise, assign "Invalid Score".
if index.size > 0:
    grade = L[index[0]]
else:
    grade = "Invalid Score"

print("Grade:", grade)

相关问题