1

I would like to write a short code (maybe with the use of numpy or any other mathematical package) for calculating a score I recive in python according to the 4 GPA formola like in the link

Means that, If Im receing this list of scores:

[95,100,80,42]

Ill receive this result:

[4.0,4.0,2.7,0.0]
Dor Cohen
  • 142
  • 5
  • Please [edit] your question with the specific attempt you've made so far at doing this and a detailed explanation of where you're stuck, thanks! – BigBen Nov 12 '21 at 17:22
  • What have you tried based on your own research, and what went wrong with your attempts? Please [edit] your question to include a [mcve] so that we can offer specific help – G. Anderson Nov 12 '21 at 17:23

2 Answers2

1

Pure NumPy solution using np.digitize:

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)]))

Output:

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

EDIT: You can alternatively use np.searchsorted, which should be a faster since it does less checks on the inputs, the code is almost identical:

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')]))

Output:

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

Complexity: Both np.digitize and np.searchsorted applies binary search to bin values, which results in a O(nlogm) worst case complexity. Whereas for loops and if checks has a O(nm) worst case complexity. Here n is the length of inputs, and m is the length of bins.

Naphat Amundsen
  • 1,519
  • 1
  • 6
  • 17
-1
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)

output

4.0
4.0
3.0
1.0

Here I have used a list and created a Function where it will check the condition and give output

Kiran Jadhav
  • 29
  • 1
  • 1
  • 6