2

I have a file with a lot of numbers:

0.98
0.23
0.10
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
10.3
11.9
0.56
...

I want to print the number of line where the number 0 is repeated 10 consecutive times (as minimum). Consdering the above input, the output will be: 4 (for the line number 4 and because 0 es repeated 10 consecutive times). The files list.txt is a huge file. I'm new in Python. How can I do delete the error in the follow script:

import ast
values = open("list.txt","r")
values = list(map(int, ast.literal_eval(values.read().strip())))
count=0
length=""
if len(values)>1:
    for i in range(1,len(values)):
       if values[i-1]==values[i]:
          count+=1
       else :
           length += values[i-1]+" repeats "+str(count)+", "
           count=1
    length += ("and "+values[i]+" repeats "+str(count))
else:
    i=0
    length += ("and "+values[i]+" repeats "+str(count))
print (length)
martineau
  • 119,623
  • 25
  • 170
  • 301
Hdez
  • 151
  • 7
  • "The files list.txt is a huge file" - then do it line-by-line. Also are you interested in the first occurrence (line number 4 in this case), or all occurrences of the pattern? – Jan Stránský Aug 25 '20 at 20:39
  • I want to read the file line by line, and stop when it finds a number 0 is repeated 10 consecutive times, and that's all, no matter all ocurrences of the pattern. – Hdez Aug 25 '20 at 20:43

2 Answers2

0

Read and evaluate the file line by line. If the pattern is found, the loop is broken, stopping reading the file

import ast
count = 0
lineNb = -1
found = False # False by default
with open("list.txt") as f:
    for i,line in enumerate(f): # loop over lines, one-by-one
        value = ast.literal_eval(line)
        if value == 0:
            if count == 0: # first occurrence
                lineNb = i # set potential lineNb
            count += 1     # increment counter
            if count == 10: # desired condition
                found = True # now we know we have found the pattern
                break        # break the for loop
        else: # not 0
            count = 0 # reset counter

print(found,lineNb) # (True,3) # lineNb is zero-based, 3 = 4th line
Jan Stránský
  • 1,671
  • 1
  • 11
  • 15
0
with open('consecutive.txt') as f:
    c = 0
    for i,line in enumerate(f):
        if float(line)==0.0:
            c+=1
            if c == 10:
                print(i-8)
                break
        else:
            c=0

Output

4
Chris
  • 15,819
  • 3
  • 24
  • 37