Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Picking repeated adjacent numbers in a list

I want to enter a group of numbers, and my output to be a list of the numbers that are repeated more than once, side by side.

Example input: 1,1,2,2,1,1,1,3,4,5,5,-1,-1,-1,3,4,3

Wanted output: [1,2,1,5,-1]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My code:

countnumbers = []
numbers = input().split(',')

for i in range(len(numbers)):
    numbers[i] = int(numbers[i])

sizeoflist = len(numbers)
  
for i in range(sizeoflist - 1):
    if numbers[i] == numbers[i + 1]:
        countnumbers.append(numbers[i])
                
mylist = str(countnumbers).replace(' ','')
print(mylist)

Example for what my code generates:

Input: 1,1,1,2,2,1,1,1

Output: [1,1,2,1,1]

So I’m just struggling in how to make it [1,2,1].
I know my code is faulty, I tried using the count function, to count but didn’t work for me.
And please without the def calling function.

>Solution :

Add a way to remember last known number:

countnumbers = []
numbers = input().split(',')

for i in range(len(numbers)):
    numbers[i] = int(numbers[i])

sizeoflist = len(numbers)

current = None
for i in range(sizeoflist - 1):
    if numbers[i] == numbers[i + 1]:
        if current is None:
            current = numbers[i]
            countnumbers.append(numbers[i])
    else:
        current = None

mylist = str(countnumbers).replace(' ','')
print(mylist)

notice how i used current variable

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading