user11502296
user11502296

Reputation:

Print the indices of a given element in an array using recursion?

I am trying to write code for returning an array of all indices of a given element in an array

arr = [15,11,40,4,4,9]
x = 4
# fsf means count of element 'found so far'
def all_index(arr, i , x, fsf):
    if i == len(arr):
        result = [0] * fsf 
    
    elif arr[i] == x:
        indices = all_index(arr, i + 1, x, fsf + 1)
        indices[fsf] = i
        return indices
        
    else:
        indices = all_index(arr, i + 1, x, fsf)
        return indices
        
        
print(all_index(arr, 0, x, 0))

This question already has answers here: Recursive function returning none in Python [duplicate] (2 answers)

Your post has been associated with a similar question. If this question doesn’t resolve your question, ask a new one.

Closed 3 hours ago.

(Private feedback for you) Edit question

I am trying to write code for returning an array of all indices of a given element in an array. fsf means count of element 'found so far'

arr = [15,11,40,4,4,9]
x = 4

def all_index(arr, i , x, fsf):
    if i == len(arr):
        result = [0] * fsf 
    
    elif arr[i] == x:
        indices = all_index(arr, i + 1, x, fsf + 1)
        indices[fsf] = i
        return indices
        
    else:
        indices = all_index(arr, i + 1, x, fsf)
        return indices
        
        
print(all_index(arr, 0, x, 0))

Expected output: [3,4]

To my understanding, the indices array is [0,0] but later it must change to [3,4]

While the code is easy using iteration, I am trying to learn recursion.

Upvotes: 0

Views: 407

Answers (1)

Saurav Sahu
Saurav Sahu

Reputation: 13954

You can simply append the index into an array at each recursion where value matches current element of array:

ans = []
def all_index(arr, i, x):
    if i is len(arr): return;
    if x is arr[i]:
        ans.append(i)
    all_index(arr, i+1, x)


all_index(arr, 0, x)
print(ans)

Upvotes: 1

Related Questions