1

I'm quite new to Python, and doing a Udemy course on coding interview challenges. This one is a linear search through a 2D array in Python. If I enter 11 as an argument, it finds it at position [0][0] - which is correct. However, if I change the argument to another number that is in the array, it returns 'The element has not been found.' I am pretty sure that I have entered the same code as the instructor, but I must have done something wrong, as his works and mine doesn't! I would be really grateful if someone could help me find my error! Thanks so much!


Quick edit to say thanks to everyone who has taken the time to help me with this. So great to have the support! Have a great day!
twoDArray = np.array([[11, 15,10, 6], [10, 14, 11, 5], [12, 17, 12, 8], [15, 18, 14, 9]])
print(twoDArray)

def searchTDArray(array, value):
    for i in range(len(array)): # Return number of rows.
        for j in range(len(array[0])): # Return number of columns.
            if array[i][j] == value:
                return 'The value is located at index' +str([i])+str([j])
            else:
                return 'The element has not been found.'

print(searchTDArray(twoDArray, 11))
4
  • 2
    Your method will return at [0][0] in all cases. You must put the second return outside the loops. Commented Jun 5, 2021 at 9:10
  • 2
    You need to return 'The element has not been found.' only once when you have visited all the indexes, that is outside both the for loop. Commented Jun 5, 2021 at 9:10
  • 1
    Your method will only work if the element you are trying to find only exists in [0][0] index, even if it is present in any other index, it will return as not present. Commented Jun 5, 2021 at 9:13
  • HA! Brilliant! Thank you! That's where I thought I had it originally, BUT, it was actually inside the 1st for loop, indented to the same level as the 2nd one. Thanks so much for taking time out of your day to help a noob! Commented Jun 5, 2021 at 9:17

5 Answers 5

2

You should return 'the element has not been found' only after checking all the values, so you must remove the else, and push the second return outside of the for loops

Sign up to request clarification or add additional context in comments.

1 Comment

Because otherwise, if it doesn't find the first time, it will enter the else statement and return that nothing has been found, without even looking to other values
1

Do not return in else. Program will return immediately after index 0, 0. Return fail value after both loops are done.

Comments

1

First, I would recommend on using the built-in numpy functionality (np.where):

twoDArray = np.array([[11, 15,10, 6], [10, 14, 11, 5], [12, 17, 12, 8], [15, 18, 14, 9]])
print(np.where(twoDArray == 11)

In case you wish to stay with the for loops you should use the return statement only in the end of the nested loops, so that you will be able to find all the positions of element you are looking for, and so that it will not break because of the else. I would do something like:

def searchTDArray(array, value):
    pos = []
    for i in range(len(array)): # Return number of rows.
        for j in range(len(array[0])): # Return number of columns.
            if array[i][j] == value:
                pos.append((i,j))
    if len(pos) == 0:
        return 'The element has not been found.'
    else:
        return pos
 

print(searchTDArray(twoDArray, 11))

Comments

1

Based on your codes, I have a solution which can also tell you the number of occurrences of the target element. One thing to notice is that I did not use "return" within the nested loops, because if the condition is met, the loop will just stop there.

def searchTDArray(array, value):
    count = 0 # initialize a number count
    for i in range(len(array)): # Return number of rows.
        for j in range(len(array[0])): # Return number of columns.
            if array[i][j] == value:
                print('The value is located at index' +str([i])+str([j]))
                count += 1 # whenever you find one target element, add 1 to the number count
            else: 
                continue
    if count >= 1: 
        return "The number of occurences:",count
    else: 
        return "The element has not been found in the whole dataset."

Comments

1

Your fail-condition is misplaced breaking out of your function immediately.

You should use numpy.where to find all indexes a certain condition holds:

import numpy as np
twoDArray = np.array([[11, 15,10, 6], [10, 14, 11, 5],
                      [12, 17, 12, 8], [15, 18, 14, 9]])


def searchTDArray(array, value):
    w = np.where(array == value)
    coords = list(zip(*w)) # [0] to find only first
    return coords or 'The element has not been found.'

print(searchTDArray(twoDArray, 11))
print(searchTDArray(twoDArray, 42))

Output:

[(0, 0), (1, 2)]
The element has not been found.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.