Home > Enterprise >  I have a problem with the for loop PYTHON
I have a problem with the for loop PYTHON

Time:12-08

I have a problem when using the for loop, i dont 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 recives an array of integers and another integer wich I call target, the script has to give me back the position in the array in wich 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 might be 2, because the number of the target (5) is in the position "2" of the array.

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

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

CodePudding user response:

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

CodePudding user response:

you could use enumerate which gives you the index and value

class Solution:
    def searchInsert(nums, target):
        for index, value in enumerate(nums):
            if value == target:
                return index 
             
print(Solution.searchInsert([1,3,5,6], 5))

CodePudding user response:

I am posting here just fixed code but as others pointed out, its a strange way to deal with it. But I understand, if you learn Python and come from other language (Visual Basic?), one would go this way. In python indent is crucial. In your code, you need to increase pos everytime code goes through cycle, not only when you find/did not find the value you want.

class Solution:
    def searchInsert(nums, target):
        pos = 0
        for i in nums:
            if nums[pos] == target:
                print(pos) #replace with return pos ?
                break
            pos = pos   1 #increase outside above condition

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

To make this code easier, one liner, investigate other users comments. Or research array index, length and later pandas module.

CodePudding user response:

The problem with your code is when the for loop reaches the target number in the list(like 5 in this example) it won't execute pos 1 because the condition(infront of if) has turned False. So it will return the position of the item in the list that is before the target.

My solution may seems foolish, but if you change the initial value of pos from 0 to 1, it will solve the problem!

  • Related