Search code examples
pythonarraysfor-loopinserttarget

I have a problem with the for loop Python


I have a problem when using the for loop, I don't know why my loop is not working as expected.

CODE:

class Solution:
    def searchInsert(nums, target):
        pos = 0
        for i in nums:
            if nums[pos] != target:
                pos = pos + 1
                
            print(pos)
            break

Solution.searchInsert([1,3,5,6], 5)

This program receives an array of integers and another integer which I call target, the script has to give me back the position in the array in which we have the number of the target.

In this case my array "nums" contains [1,3,5,6] and my target is 5, so the result must be 2, because the number of the target (5) is in the position "2" of the array.

The problem comes when I run the script. Instead of a 2 the script gives me a 1

If someone catches the error in the code please tell me.


Solution

  • You are closing the loop after the first iteration: you need to add an else: block so it can keep going until the condition is met...

    class Solution:
        def searchInsert(nums, target):
            pos = 0
            for i in nums:
                if nums[pos] != target:
                    pos = pos + 1
                else:    
                    print(pos)
                    break
    
    >>> Solution.searchInsert([1,3,5,6],5)
    2