Simplify the directory path ( Unix like ) | function to simplify a Unix - styled absolute path ; using vector in place of stack ; forming the current directory . ; if " . . " , we pop . ; do nothing ( added for better understanding . ) ; push the current directory into the vector . ; forming the ans ; vector is empty ; absolute path which we have to simplify .
def simplify ( path ) : NEW_LINE INDENT v = [ ] NEW_LINE n = len ( path ) NEW_LINE ans = " " NEW_LINE for i in range ( n ) : NEW_LINE INDENT Dir = " " NEW_LINE while ( i < n and path [ i ] != ' / ' ) : NEW_LINE INDENT Dir += path [ i ] NEW_LINE i += 1 NEW_LINE DEDENT if ( Dir == " . . " ) : NEW_LINE INDENT if ( len ( v ) > 0 ) : NEW_LINE INDENT v . pop ( ) NEW_LINE DEDENT DEDENT elif ( Dir == " . " or Dir == " " ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT v . append ( Dir ) NEW_LINE DEDENT DEDENT for i in v : NEW_LINE INDENT ans += " / " + i NEW_LINE DEDENT if ( ans == " " ) : NEW_LINE INDENT return " / " NEW_LINE DEDENT return ans NEW_LINE DEDENT Str = " / a / . / b / . . / . . / c / " NEW_LINE res = simplify ( Str ) NEW_LINE print ( res ) NEW_LINE