Weird behavior with a lot of numbers python

Viewed 104

So I wrote a code that checks how much times in a list is the same number repeating in a row and when it gets that it divides them with a user inputted number and then sums all the numbers in a list. It all works until I got to the larger numbers then it just started not counting the last few numbers.

N = int(input())
Ai = input()
arr = [int(x) for x in Ai.split()]
c = 0
final = []
final2 = []
d = []
b = len(set(arr)) 
frozen_num = arr[0]
for i in range(0, len(arr) + b):
    try:
        if frozen_num == arr[0]:
            arr.remove(arr[0])
            c+=1
        else:
            final.append(c)
            frozen_num = arr[0]
            c = 0 
    except:
        pass
final.append(c)
for l in final:
    d.append(l/N)
final2 = map(int, d)
print(sum(final2))

Input: User chosen dividing number: "3", List of number ["5, 5, 5, 5, 4, 4, 4, 2, 2]

Output: 2

But when I gave it an input: 20 38 66 66 66 66 66 66 66 66 13 13 13 13 13 13 13 13 13 13 13 43 43 43 43 43 43 22 22 22 98 98 98 98 98 98 77 7 7 7 7 7 7 7 7 7 7 7 82 82 82 82 26 47 41 38 38 38 57 57 57 79 79 79 79 79 79 79 79 79 79 79 79 79 79 98 98 98 98 98 98 98 98 13 67 67 67 67 80 80 80 80 80 50 50 50 50 50 50 50

It gave me an output: 25 and not 26.

Because it didn't count the last few numbers correctly.

It would be a lot of help if someone could explain this behavior.

1 Answers

A few points can be simplified from your code. First, the init part: you initialise final2and d before looping and then use them for the first time after the loop by assigning them a new value. The init part can be reduced to:

N = int(input())
Ai = input()
arr = [int(x) for x in Ai.split()]
c = 0
final = []
b = len(set(arr)) 
frozen_num = arr[0]

Instead of deleting items from arr, you can simply iterate through it:

for i in arr:
    if frozen_num == i:
        c+=1
    else:
        final.append(c)
        frozen_num = i
        c = 1

I dropped the try/except block because it seems that you put it while trying to find the right input for the range function, but you can put it back if I have overlooked something. Note that c=0 is now c=1, to count the element right away instead of looping twice on it.

Finally, use a list comprehension to initialise d : d = [l/N for l in final].

Doing these three modifications, I now get 26 instead of 25 on your example. Turns out, your range input was not right: you could loop len(arr) + b+2 times on your example: try it, and you'll get 26.

The final code:

N = int(input())
Ai = input()
arr = [int(x) for x in Ai.split()]
c = 0
final = []
b = len(set(arr)) 
frozen_num = arr[0]
for i in arr:
    if frozen_num == i:
        c+=1
    else:
        final.append(c)
        frozen_num = i
        c = 1
final.append(c)
d = [l/N for l in final]
final2 = map(int, d)
print(sum(final2))
Related