if elif 在 python 中通过堆栈问题循环遍历 for 循环时

if elif when looping thru for loop with stack problem in python

问题出在这里:

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 "/"

我的正确解法:

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

在此测试用例上 - ["..","..","..","..","..","..","."],下面的代码

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

预期的结果是 [],但我的代码给出了 [".."] - 错误的结果。

输入的不是字符串,for 循环可能会将“..”与“.”弄错。 - 1 点和 2 点。

输入的是一个列表,顺便说一句,它应该清楚地区分“..”和“.”。 - 所以我假设 if/elif 并不重要。

为什么简单地将 elif 替换为“if”会给出错误的结果?

if-elif-elseif-if-else其实是有区别的。 简单来说,if-elif-else被视为“一体”,而if-if-else实际上是两个条件块:ifif-else

首先我们看一下if-elif-else版本。如果s"..",它永远不会到达-elif-else里面的代码。懂事。

然而,对于 if-if-else 版本的代码,正如我们所说,它实际上经历了两个 if-else 逻辑块。如果 s"..",它首先通过第一个 if 语句。然后它继续下一个 if-else 块。由于 s 不等于 ".",因此它继续执行 else 块中的代码,我相信这不是您想要的。