Madridista
Madridista

Reputation: 7

Why this code takes very long time to run?

I have a list [4,73,67,38,33]

and I want to round up this list by using function called gradingStudents. The code is like this

def gradingStudents(grades):
    for grade in grades:
        if grade < 38:
            grades.append(grade)
        else:
            roundgrade = round(grade/5)*5
            if roundgrade - grade < 3:
                grades.append(roundgrade)
            else:
                grades.append(grade)
    return grades

grades = []
gradingStudents([4,73,67,38,33])
print(grades)

The expected output is like this [4,75,67,40,33]

The problem is the code really takes long time to run. What mistake just I did? Can you figure out?

Upvotes: 0

Views: 83

Answers (3)

Jan Christoph Terasa
Jan Christoph Terasa

Reputation: 5935

Make your life easier, and seprate the list creation/modification part and the recalculation part.

Create a function for your intended recalculation:

def round_grade(grade):
    if grade >= 38:
        rounded = round(grade / 5) * 5
        if rounded - grade < 3:
            return rounded
    return grade

Then just map it to all elements of your list:

grades = [4, 73, 67, 38, 33]
new_grades = list(map(round_grade, grades)) # [4, 75, 65, 40, 33]

Upvotes: 0

Madridista
Madridista

Reputation: 7

I made a mistake in my function. The code should be like this

def gradingStudents(grades):
    result = []
    for grade in grades:
        if grade < 38:
            result.append(grade)
        else:
            roundgrade = round(grade/5)*5
            if roundgrade - grade < 3:
                result.append(roundgrade)
            else:
                result.append(grade)
    return result
print(gradingStudents([4,73,67,38,33]))

It will work as I expected

Upvotes: 1

Dominique
Dominique

Reputation: 17501

You are doing this:

for each grade in grades:
  grades.append(...)

This goes through your list and keeps on appending and making it longer (which is not what you want: you start with a list of five and want to finish with a list of five).

So you should be doing this: (pseudo-code)

for (int i = 0 to grades.length() - 1):
  if grades[i] == ...
  then grades[i] = ...

In this way you will replace the items in your list instead of appending.

Upvotes: 0

Related Questions