avatar Bite 309. A simple document class

When we want to transform our data often, method chaining is a wonderful paradigm that allows us to write elegant and less error-prone code.

For example, given a string s, we can do the following in Python s.strip().lower().split().

When working with databases, we often have code snippets like the next one:

session.query(Engineer).\
  filter(Engineer.id == Employee.id).\
  filter(Employee.name == 'dilbert').\
    delete()

Implementing method chaining is not hard, although there are at least two different ways of achieving this functionality.

Now it's your turn to try it out.

Tasks

In this Bite you are asked to implement a simple document class that can be used to create text documents.

For this Bite, a document is a list of strings, each string representing exactly one line.

The order in the list is the order of the document. Indices start at 0.

However, because working with documents basically means a lot of repeated function calls, you want to provide at least some convenience by offering method chaining.

Be aware that there are (at least) two ways to achieve method chaining and you can choose which one you want to implement here. Both will pass the tests.

With method chaining it is easy to execute multiple transformations of a document at once:

d = (
  Document()
  .add_line("My first sentence.")
  .add_line("My second sentence.")
  .add_line("Introduction", 0)
  .merge_lines([1,2])
)
print(d)
>>> Introduction
>>> My first sentence. My second sentence
print(len(d))
>>> 2
print(d.word_count())
>>> 7
print(d.words)
>>> ['first', 'introduction', 'my', 'second', 'sentence']

We provided you with a skeleton of a Document class that offers typical methods for manipulating documents. 

For this bite, we only consider methods that change whole lines, which makes things a lot easier.

Feel free to add more methods to your liking.

If you wonder why there is no method for undoing the last action, stay tuned for another Bite!

Happy coding.

Login and get coding
go back Intermediate level
Bitecoin 3X

19 out of 20 users completed this Bite.
Will you be Pythonista #20 to crack this Bite?
Resolution time: ~78 min. (avg. submissions of 5-240 min.)
Pythonistas rate this Bite 7.0 on a 1-10 difficulty scale.
» Up for a challenge? 💪

We use Python 3.8