0

I've been trying to run a list of numbers through the below code to convert different numbers to certain allowed numbers, but there must be a better way than this.

goalNum = [-3, 0, 2, 4, 7, 10, 12]

def roundGrade(grades):
    gradeRounded = []
    for i in grades:
        if i < -1.5:
            gradeRounded.append(-3)
        elif -1.5 <= i < 1:
            gradeRounded.append(0)
        elif 1 <= i < 3:
            gradeRounded.append(2)
        elif 3 <= i < 5.5:
            gradeRounded.append(4)
        elif 5.5 <= i < 8.5:
            gradeRounded.append(7)
        elif 8.5 <= i < 11:
            gradeRounded.append(10)
        elif 11 <= i <= 12:
            gradeRounded.append(12)
    gradeRounded = np.array(gradeRounded)
    return gradeRounded

For now i've gone through by just appending the corresponding rounded grade to a new vector, and then just using that, but i'd like to shorten it down a bit.

Chris
  • 1
  • @mkrieger1 Not the best dupe. This would have to apply that solution repeatedly, for which there must be a better approach than this quadratic solution. Also, min would take the first of two equally close values. This asks for the second, as it wants to round up in that case. – user2390182 Aug 18 '21 at 13:54
  • A better approach is for example a binary search, which is also shown in the second-highest voted answer. – mkrieger1 Aug 18 '21 at 14:04
  • True dat... closing. – user2390182 Aug 18 '21 at 14:05

0 Answers0