Some time ago I have started to learn Python. Today, I will present a way to solve the problem “Reduce file path”.
The 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:
My code is below:
sResult = path
sDots = ".."
#Removing double "/"
sResult = ''.join([sResult[i] for i in range(len(sResult)-1) if sResult[i+1] != sResult[i] or sResult[i]!="/"]+[sResult[-1]])
#Removing double .. - one directory back
while sDots in sResult:
iPosition = sResult.rfind(sDots)
if iPosition == 1:
sResult = sResult[3:]
sResult = sResult[:iPosition-1] + sResult[(iPosition+4):]
sResult = sResult[:iPosition-1]
#Removing directory point = ./
sResult = sResult.replace("./","")
#Removing last "/"
if len(sResult)>1 and sResult[-1:]=="/":
sResult = sResult[:-1]
Enjoy it! 🙂