[Tutor] Help required to count no of lines that are until 1000 characters

Dave Angel davea at ieee.org
Wed May 12 04:23:31 CEST 2010


ramya natarajan wrote:
> Hello,
>
> I am very  beginner to programming, I  got task to Write a loop that 
> reads
> each line of a file and counts the number of lines that are read until 
> the
> total length of the lines is 1,000 characters. I have to read lines from
> files exactly upto 1000 characters.
>
> Here is my code:
>  I created file under /tmp/new.txt  which has 100 lines and 2700 
> characters
> , I wrote code will read exactly 1000 characters and count lines upto 
> those
> characters.But the problem is its reading entire line and not stopping
> excatly in 1000 characters. Can some one help what mistake i am doing 
> here?.
>
>    log = open('/tmp/new.txt','r')
>    lines,char = 0,0
>    for line in log.readlines():
>         while char < 1000 :
>                 for ch in line :
>                      char += len(ch)
>                 lines += 1
>   print char , lines
>   1026 , 38  ----  Its counting entire line  instead of character upto 
> 1000
> -- can some one point out what mistake am i doing here , where its not
> stopping at 1000 . I am reading only char by car
>
> My new.txt -- cotains content like
> this is my new number\n
>
> Can some one please help. I spent hours and hours to find issue but i 
> am not
> able to figure out, Any help would be greatly appreciated.
> Thank you
> Ramya
>
>   
The problem is ill-specified (contradictory).  It'd probably be better 
to give the exact wording of the assignment.

If you read each line of the file, then it would only be a coincidence 
if you read exactly 1000 characters, as most likely one of those lines 
will overlap the 1000 byte boundary.


But you have a serious bug in your code, that nobody in the first five 
responses has addressed.  That while loop will loop over the first line 
repeatedly, till it reaches or exceeds 1000, regardless of the length of 
subsequent lines.  So it really just divides 1000 by the length of that 
first line.  Notice that the lines += 1 will execute multiple times for 
a single iteration of the for loop.

Second, once 1000 is reached, the for loop does not quit.  So it will 
read the rest of the file, regardless of how big the file is.  It just 
stops adding to lines or char, since char reached 1000 on the first line.

The simplest change to your code which might accomplish what you want is 
to put the whole thing inside a function, and return from the function 
when the goal is reached.  So instead of a while loop, you need some 
form of if test.  See if you can run with that.  Remember that return 
can return a tuple (pair of numbers).

There are plenty of other optimizations and approaches, but you'll learn 
best by incrementally fixing what you already have.

DaveA


>


More information about the Tutor mailing list