0

I want to return a new array from another array by rounding the value near to 5 and it shouldn't round if the rounded number is less then 40. but it is showing "IndexError: list assignment index out of range" error .

import os
import sys

#
# Complete the gradingStudents function below.
#
def gradingStudents(grades):
    def round_to_next5(n):
        return n + (5 - n) % 5
    j = len(grades)
    r = [j]
    for i in range(0,len(grades)):
        roundi = round_to_next5(grades[i])
        dif = roundi - grades[i]
        if dif < 3 and roundi > 40:
            r[i] = roundi
            print("working1")
        else:
            r[i] = grades[i]
            print("working2")
    return r
if __name__ == '__main__':
    f = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input())

    grades = []

    for _ in range(n):
        grades_item = int(input())
        grades.append(grades_item)

    result = gradingStudents(grades)

    f.write('\n'.join(map(str, result)))
    f.write('\n')

    f.close()

Expected an array but it's showing an error.

martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

0

Try this one. r = [j] is culprit of error. I have used numpy to create a zeros array and if you do not have numpy install it by the following command pip install numpy

Full working code is given below.

    import os
    import sys
    from numpy import zeros
    #
    # Complete the gradingStudents function below.
    #
    def gradingStudents(grades):
        def round_to_next5(n):
            return n + (5 - n) % 5
        j = len(grades)
        r = zeros(j)
        for i in range(0,len(grades)):
            roundi = round_to_next5(grades[i])
            dif = roundi - grades[i]
            if dif < 3 and roundi > 40:
                r[i] = roundi
                print("working1")
            else:
                r[i] = grades[i]
                print("working2, i: ", i)
        return r
    if __name__ == '__main__':
        f = open('text.txt', 'w')

        n = int(input())
        print('Got user input')
        grades = []

        for _ in range(n):
            grades_item = int(input())
            grades.append(grades_item)

        print('Len of grades is: ', len(grades))
        result = gradingStudents(grades)

        f.write('\n'.join(map(str, result)))
        f.write('\n')

        f.close()
SyntaxVoid
  • 2,501
  • 2
  • 15
  • 23
Rheatey Bash
  • 779
  • 6
  • 17
0

The most likely cause of your IndexError is at one of the assignments to r[i]. This will cause this error whenever the length of grades is greater than one. The problem is that r is initialised to be a list containing a single number (the length of grades).

I think you intended to initialise r to be a list of length j, not containing j, for example:

r = [0 for _ in range(j)]
Corin
  • 2,417
  • 26
  • 23
Steven Fontanella
  • 764
  • 1
  • 4
  • 16