Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Write a function longest_line(name) that gives the longest line of a file, without its new line. For an empty file, it gives the empty text. If two lines are equally long, it gives the first one.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. Go through the lines and keep the best so far. The test is > (strictly more), so that a later line of the same length does not replace the first.
Check. the longest line has 16 characters, and another long line has 17. So the answer is another long line. The empty file never enters the loop and gives ''.
Answer: another long line, and ''.
Log in to join the discussion.
Loading…