Home > Back-end >  if elif when looping thru for loop with stack problem in python
if elif when looping thru for loop with stack problem in python

Time:04-27

the problem is here:

https://binarysearch.com/problems/Unix-Path-Resolution

Given a Unix path, represented as a list of strings, return its resolved version.

In Unix, ".." means to go to the previous directory and "." means to stay on the current directory. By resolving, we mean to evaluate the two symbols so that we get the final directory we're currently in.

Constraints

  • n ≤ 100,000 where n is the length of path

Example 1
Input

path = ["usr", "..", "usr", ".", "local", "bin", "docker"]

Output

["usr", "local", "bin", "docker"]

Explanation

The input represents "/usr/../usr/./local/bin" which resolves to "/usr/local/bin/docker"

Example 2
Input

path = ["bin", "..", ".."]

Output

[]

Explanation

The input represents "/bin/../.." which resolves to "/"

my correct solution:

class Solution:
    def solve(self, path):
        
        stack = []

        for s in path:
            if s == "..":
                if len(stack)> 0:
                    stack.pop()
            elif s == ".":                   #if "elif" is replaced with "if" - it gives error
                continue
            else:
                stack.append(s)
        print(stack)
        return stack

on this test case - ["..","..","..","..","..","..","."], the below code

class Solution:
    def solve(self, path):
        
        stack = []

        for s in path:
            if s == "..":
                if len(stack)> 0:
                    stack.pop()
            if s == ".":                   # "elif" is replaced with if and gives error
                continue
            else:
                stack.append(s)
        print(stack)
        return stack

the expected result is [], but my code gives [".."] - wrong result.

The input is not a string where a for loop can mistake ".." vs "." - 1dot and 2dot.

The input is a list and it should clearly distinguish btw ".." and "." - so i assumed if/elif is not critical.

why does simple replacing elif with "if" gives wrong result?

CodePudding user response:

There is actually differences between if-elif-else and if-if-else. In simple terms, if-elif-else is regarded as "one body" while if-if-else is in fact two conditional blocks: if and if-else.

First we look at the if-elif-else version. If s is "..", it will never reach the code inside -elif or -else. Sensible.

However for the if-if-else version of code, as we said it actually goes through two blocks of if-else logic. If s is "..", it first goes through the first if statement. Then it proceed to the next if-else block. Since s does not equal ".", so it proceeeds to the code in the else block, which is I believe not what you want.

  • Related