Home > Software engineering >  Why is my code not following the command?
Why is my code not following the command?

Time:03-17

def pairs(x):
  for num in x:
    if num == num :
     return x

y = [2, 2, 2, 2, 2, 4, 3, 3]
pairs (y)
print (y)

this is returning [2, 2, 2, 2, 2, 4, 3, 3] but I want to return [2,2,3] I've tried 3 codes already other than this one help me

CodePudding user response:

Your code seems to be intended to find all the numbers that exist in pairs in the list. The best way would be (for a sorted list) to just cycle through the list and check successive elements.
Your code just matches if the current number is the same as the current numbers always returns true and returns all elements. A correct Code might be:

y = [2, 2, 2, 2, 2, 4, 3, 3]
y=sorted(y) # Sorts the given list

def pairs(arr):
    i = 0 # Counter variable
    res = [] #result list
    while i < len(arr)-1:
        if arr[i] == arr[i 1]: 
            res.append(arr[i]) # If the successive elements are the same, add 
                               # it to the result array and since we have already 
                               # checked the next element, increment the counter by 
                               # two
            i =2
        else:
            i =1 # If the elements are different we need to check the 
                 # next element as well so increment by 1
    return res
    
print(pairs(y))

CodePudding user response:

You are comparing the element with itself which is always true. Here is the correct logic

y = [2, 2, 2, 2, 2, 4, 3, 3]
filt = []
i=0
while (i< (len(y)-1)):
    if y[i] == y[i 1]:
        filt.append(y[i])
        i =1
    i =1    
print(filt)        
  • Related