【问题标题】:Numpy: change score to 4 GPA score [duplicate]Numpy:将分数更改为 4 GPA 分数 [重复]
【发布时间】:2021-12-25 00:40:18
【问题描述】:

我想编写一个简短的代码(可能使用numpy 或任何其他数学包)根据link 中的4 GPA 公式计算我在python 中获得的分数

意思是,如果我收到这个分数列表:

[95,100,80,42]

我会收到这个结果:

[4.0,4.0,2.7,0.0]

【问题讨论】:

  • edit 提出您迄今为止所做的具体尝试,并详细说明您遇到的问题,谢谢!
  • 根据您自己的研究,您尝试过什么,您的尝试出了什么问题?请edit您的问题包括minimal reproducible example,以便我们提供具体帮助

标签: python numpy


【解决方案1】:

使用np.digitize 的纯 NumPy 解决方案:

import numpy as np
scores = [95, 100, 80, 42, 39, 96, 80, 69]
bins = [64, 66, 69, 72, 76, 79, 82, 86, 89, 92, 96, 100]
gpa_scale = np.array([0.0, 1.0, 1.3, 1.7, 2.0, 2.3, 2.7, 3.0, 3.3, 3.7, 4.0, 4.0])
print(repr(gpa_scale[np.digitize(scores, bins, right=True)]))

输出:

array([4. , 4. , 2.7, 0. , 0. , 4. , 2.7, 1.3])

编辑: 您也可以使用np.searchsorted,它应该更快,因为它对输入的检查更少,代码几乎相同:

import numpy as np
scores = [95, 100, 80, 42, 39, 96, 80, 69]
bins = [64, 66, 69, 72, 76, 79, 82, 86, 89, 92, 96, 100]
gpa_scale = np.array([0.0, 1.0, 1.3, 1.7, 2.0, 2.3, 2.7, 3.0, 3.3, 3.7, 4.0, 4.0])
print(repr(gpa_scale[np.searchsorted(bins, scores, side='left')]))

输出:

array([4. , 4. , 2.7, 0. , 0. , 4. , 2.7, 1.3])

复杂性: np.digitizenp.searchsorted 都将二进制搜索应用于 bin 值,这会导致 O(nlogm) 最坏情况的复杂性。而 for 循环和 if 检查具有 O(nm) 最坏情况复杂性。这里n是输入的长度,m是bin的长度。

【讨论】:

    【解决方案2】:
    list1 = [95, 100, 80, 42]
    
    
    def GPA(inp):
        for i in list1:
            if i >= 90:
                print(4.0)
            elif i >= 80:
                print(3.0)
            elif i >= 70:
                print(2.0)
            else:
                print(1.0)
    
    
    GPA(list1)
    

    输出

    4.0
    4.0
    3.0
    1.0
    

    这里我使用了一个列表并创建了一个函数,它将检查条件并给出输出

    【讨论】:

    • 不考虑链接中的所有案例
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-07
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    相关资源
    最近更新 更多