简体   繁体   中英

Why is my code not checking every value in list?

I'm trying to check how much times does some value repeat in a row but I ran in a problem where my code is leaving the last number without checking it.

Ai = input()

arr = [int(x) for x in Ai.split()]
c = 0

frozen_num = arr[0]
for i in range(0,len(arr)):
    print(arr)
    if frozen_num == arr[0]:
        arr.remove(arr[0])
        c+=1
    else:
        frozen_num = arr[0] 
           
        
print(c)

So let's say I enter: 1 1 1 1 5 5 My code will give an output 5 and not 6

I hope you understand what I'm saying. I'm pretty new to python and also this code is not finished, later numbers will be appended so I get the output: [4, 2] because "1" repeats 4 times and "5" 2 times.

Edited - I accidentally wrote 6 and 7 and not 5 and 6.

You could use the Counter of the Collections module to measure all the occurrences of different numbers.

from collections import Counter
arr = list(Counter(input().split()).values())
print(arr)

Output with an input of 1 1 1 1 5 5 :

1 1 1 1 5 5
[4, 2]

If you want to stick with your method and not use external libraries, you can add an if statement that detects when you reach the last element of your array and process it differently from the others:

Ai=input()
arr = [int(x) for x in Ai.split()]
L=[]
c = 0
frozen_num = arr[0]
for i in range(0, len(arr)+1):
    print(arr)
    if len(arr)==1: #If we reached the end of the array
        if frozen_num == arr[0]: #if the last element of arr is the same as the previous one
            c+=1
            L.append(c)
        else: #if the last element is different, just append 1 to the end of the list
            L.append(c)
            L.append(1) 
    elif frozen_num == arr[0]:
        arr.remove(arr[0])
        c += 1
    else:
        L.append(c)
        c=0
        frozen_num = arr[0]
print(L)

input

[5,5,5,6,6,1]

output

[3,2,1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM