1 / 2
Oct 2020

I recently started using SPOJ, so I decided to start off with some easier problems, just to get used to the type of problems and some common algorithms. I easily managed to write a program for this problem2 in python3, but am getting a runtime error (NZEC) whenever I submit it. I’ve tried searching for common issues but I still haven’t managed to fix it. If anyone knows how, I would greatly appreciate it if they let me know.

Thanks in advance!

Code:

# SPOJ Problem CANDY Python3 Solution
import sys

# Function for getting standard input into a list
def getInput():
    res = []
    for line in sys.stdin:
        res.append(int(line))

    return res


input = getInput()

arr_pos = 0

for line in range(len(input)):
    if (line == arr_pos) and (input[line] != -1):
        case_count = input[line]
        bags = []

        sum = 0

        # Get the sum of all the bags of candy and add each bag value to a list
        for i in range(case_count):
            bags.append(input[i + 1 + arr_pos])
            sum += input[i + 1 + arr_pos]

        if case_count != 0:
            average = sum / case_count  # Get average candies per bag
        else:
            # If there are 0 bags, don't divide by 0
            average = 0

        if average % 1 != 0:
            # If average is not integer
            print(-1)
        else:
            out = 0

            # Get how much different the amount of candies each bag is from the average (how many candies extra needed per bag)
            for bag in bags:
                out += abs(average - bag)

            # Finally, since moving a candy adds one to one bag AND removes from one bag, the amount of operations needed is half of the extra candies previously calculated
            print(int(out / 2))

        arr_pos += case_count + 1
  • created

    Oct '20
  • last reply

    Oct '20
  • 1

    reply

  • 528

    views

  • 2

    users

  • 1

    link

It seems there are blank lines in the input. I modified your code to ignore them, and it then got AC.