Search code examples
pythondata-structuresdynamic-arrays

HackerRank Dynamic Array Problem - Runtime Error in the code


I am trying to solve this Dynamic Array problem on HackerRank. This is my code:

#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'dynamicArray' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts following parameters:
#  1. INTEGER n
#  2. 2D_INTEGER_ARRAY queries
#

def dynamicArray(n, queries):
    lastAnswer = 0
    a = []
    array_result = []
    for k in range(n):
        a.append([])
    
    for i in queries:
        x = i[1]
        y = i[2]
        if i[0] == 1:
            seq = ((x ^ lastAnswer) % n)
            a[seq].append(y)
        elif i[0] == 2:
            seq = ((x ^ lastAnswer) % n)
            lastAnswer = a[seq][y]
            array_result.append(lastAnswer)
    return array_result

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    first_multiple_input = input().rstrip().split()

    n = int(first_multiple_input[0])
    q = int(first_multiple_input[1])

    queries = [] # 1 0 5, 1 1 7, 1 0 3, ...

    for _ in range(q):
        queries.append(list(map(int, input().rstrip().split())))

    result = dynamicArray(n, queries)

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

    fptr.close()

I am getting a runtime error:

Traceback (most recent call last):

File "Solution.py", line 50, in

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

TypeError: 'NoneType' object is not iterable

Can anyone help me with this, I can't seem to find a solution.

This is the input:

2 5

1 0 5

1 1 7

1 0 3

2 1 0

2 1 1

Thanks.

Update: It seems like this input is working now, thanks to @cireo but the code is not working for other test cases. What the problem with this code?


Solution

  • you can try this, it works totally fine.(no runtime error)

    Replace your dynamicArray function with this code. Hopefully this will be helpful for you (^_^).

    def dynamicArray(n, queries):

    col = [[] for i in range(n)]
    res = []
    lastanswer = 0
    for q in queries:
        data = (q[1]^lastanswer)%n
        if q[0] == 1:
            col[data].append(q[2])
        elif q[0] == 2:
            ind_x = q[2]%len(col[data])
            lastanswer = col[data][ind_x]
            res.append(lastanswer)
    return res