Python – Reduce file path problem (with string slicing and list comprehension)

Some time ago I have started to learn Python. Today, I will present a way to solve the problem “Reduce file path”.

python-logo-master-v3-TMThe problem is the following – you are given a string and you should reduce it to a meaningful path for the Unix OS. Pretty much, these are the requirements of the task:


Implement a function, called reduce_file_path(path) which takes a string and returns the reduced version of the path.

  • Every .. means that we have to go one directory back
  • Every . means that we are staying in the same directory
  • Every extra / is unnecessary
  • Always remove the last /

So, I started 🙂 It was obvious that I had to elaborate over the string at least four times, each time per bullet. The trick was to decide what is the correct order of the elaborations and how to make them. Removing the double “/” was quite a difficult task, but I handled it with a complicated list comprehension. The removal of the two dots and the next slash was something quite interesting as well – with two loops and probably a lot of testing for the slicing I handled this as well. The removal of the point, was probably the easiest task, together with the removal of the last “/” where available. The code could be probably improved, but so far it returned correct values for 9 tests and I tought it is more than enough.

Here is how the result looks like:

capture-1

My code is below:

Enjoy it! 🙂

About

A VBA Developer.

Tagged with: , , ,