The function is not returning an output under the if-else condition

Question:

After applying the queries on the given array the function is not returning the resulting array(res).

”’ Reversing the Array according to the queries. Each pair of values in queries are the starting and ending indices of the given Array(Arr).

”’

Arr = [5,3,2,1,3]
Queries = [0,1,1,3,2,4]

def Reverse(Arr, Queries):
    res=[]
    for item in Arr:
        res.append(item)
    
    n = Queries[1]
    while(Queries[0] != n + 1):
        for i in range(Queries[0], Queries[1] + 1):
            res[Queries[0]] = Arr[Queries[1]]
            Queries[0] += 1
            Queries[1] -= 1
    
    Arr.clear()
    for item in res:
        Arr.append(item)
    Queries.pop(0)
    Queries.pop(0)
    #print(res)
    if len(Queries)== 0:
        return res 
    else:
        Reverse(Arr, Queries)

print(Reverse(Arr, Queries))
Asked By: Ayush Singh

||

Answers:

In your Reverse function, if len(Queries) does not equal 0, nothing is explicitly returned, so the function returns None.

Even then, you will get an IndexError because of you convoluted logic.

Instead, let’s copy arr (which is a list, rather than an array). Then we’ll iterate over the indices in queries. By giving range three arguments we specify where to start, where to stop, and the amount to increment by. If queries has length 6, i will be 0, 2, and last 4.

We can then use this to slice the list and reverse the specified sections.

def reverse(arr, queries):
  res = arr.copy()
  for i in range(0, len(queries), 2):
    res[queries[i]:queries[i+1]+1] = list(reversed(res[queries[i]:queries[i+1]+1]))
  return res
Answered By: Chris
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.