-1

Task:

You are given a sequence of N integers. Find how many elements of this sequence is equal to the first element of this sequence (do not count the first element).

N (1 ≤ N ≤ 10^6)
Those numbers do not exceed 10^9 by modulo (abs())

Examples:

input:
6
-5 7 0 -5 3 -5

output:
2

input:
6
5 7 0 -5 3 -5

output:
0

There is a memory limit and a time limit: 32MB, 1 second.

Everything is great with time. My solution is working perfectly with small tests:

input()
arr = list(map(int, input().split()))
print(arr.count(arr[0]) - 1)

With tremendous test cases, I get a Memory Limit Exceeded error. What I need to do is to get one-by-one values from one-line input and then delete them so I will not exceed the memory limit.

Question: how to get values one-by-one (not as a list) when one-line input in Python.

EDIT1 It's not a proper solution - Is there a generator version of `string.split()` in Python? . We still read the whole line. If I use that solution I get Time Limit Exceeded error. The previous version of question - Read elements one-by-one from one line

VictorMinsky
  • 26
  • 1
  • 5

1 Answers1

0

Thank you, everyone, for the list generator. I modified it for my problem. This solution works perfectly for the problem. I hope it will help someone.

import re


def split_iter():
    return (x.group(0) for x in re.finditer(r"[-0-9']+", input()))


input()
gen = split_iter()
first = next(gen)
ans = 0
for i in gen:
    if i == first:
        ans += 1
print(ans)

Test results

VictorMinsky
  • 26
  • 1
  • 5