使用Python分离括号

huangapple go评论61阅读模式
英文:

Separating parenthesis using python

问题

def split_parentheses(input_string):
    result = []
    stack = []
    for char in input_string:
        if char == '(':
            stack.append(char)
        elif char == ')':
            if len(stack) > 0 and stack[-1] == '(':
                stack.pop()
                if len(stack) == 0:
                    result.append(''.join(stack))
                    stack = []  # clear stack for the next group
            else:
                return "Invalid input string: parentheses not perfectly matched."
    if len(stack) > 0:
        return "Invalid input string: parentheses not perfectly matched."
    return result

def wrap_with_parentheses(string):
    return f'({string})'

input_string = input("Enter a string of perfectly matched parentheses and whitespace: ")
result = split_parentheses(input_string)
result = list(map(wrap_with_parentheses, result))
print(result)
英文:

Given a string consisting of groups of matched parentheses and whitespace, Write a human friendly python program to split the string into groups of perfectly matched parentheses without any whitespace.

Input:	( ()) ((()()())) (()) ()		Output:	['(())', '((()()()))', '(())', '()']
Input:	() (( ( )() ( )) ) ( ())		Output:	['()', '((()()()))', '(())']
def split_parentheses(input_string):
    result = []
    stack = []
    for char in input_string:
        if char == '(':
            stack.append(char)
        elif char == ')':
            if len(stack) > 0 and stack[-1] == '(':
                stack.pop()
                if len(stack) == 0:
                    result.append(''.join(stack))
                    stack = []  # clear stack for the next group
            else:
                return "Invalid input string: parentheses not perfectly matched."
    if len(stack) > 0:
        return "Invalid input string: parentheses not perfectly matched."
    return result

def wrap_with_parentheses(string):
    return f'({string})'

input_string = input("Enter a string of perfectly matched parentheses and whitespace: ")
result = split_parentheses(input_string)
result = list(map(wrap_with_parentheses, result))
print(result)

This doesn't display multiple groups of parenthesis with nesting like ((()()()))

答案1

得分: 2

一些问题

* 在内部的 `if` 块中栈是空的已经测试为空),所以 `''.join(stack)` 将始终是一个空字符串,并且清除栈是一个无用的操作,因为它已经是空的。

* 由于你弹出了所有的 `(` 并且栈从不接收任何 `)`,所以没有办法从栈中重建最终的字符串你需要一个单独的变量来收集括号这可以是一个字符串变量

* 用另一对括号包裹结果毫无意义因为它只是创造了与输入无关的括号所以去掉 `wrap_with_parentheses`。

其他备注

* 由于栈只接收 `(` 字符你实际上不需要这些字符它还能是什么?),只需要长度为此你可以使用一个数值变量比如 `depth`。它将对应于 `len(stack)`,而不需要实际上拥有栈

这是你代码的修改版

```python
def split_parentheses(input_string):
    result = []
    depth = 0  # 使用这个代替栈
    current = ""  # 这个变量将收集作为结果中的单个条目的字符串
    for char in input_string:
        if char in "()":
            current += char  # 收集所有的括号
        if char == '(':
            depth += 1
        elif char == ')':
            depth -= 1
            if depth < 0:
                return "无效的输入字符串:括号不匹配。"
            if depth == 0:
                result.append(current)
                current = "" # 清除字符串以便下一个组
    if depth:
        return "无效的输入字符串:括号不匹配。"
    return result


input_string = input("输入一个包含 perfectly matched 括号和空格的字符串:")
result = split_parentheses(input_string)
print(result)

<details>
<summary>英文:</summary>

Some issues:

* In the inner `if` block, the stack is empty (it was tested to be empty), so `&#39;&#39;.join(stack)` will always be an empty string, and clearing the stack is a useless operation, since it is already empty.

* Since you pop all `(` from the stack and the stack never receives any `)`, there is no way to reconstruct the final string from the stack. You need a separate variable to collect the parentheses. This could be a string variable. 

* It makes no sense to wrap the results with another pair of parentheses as it just invents parentheses that have no relation with the input. So drop `wrap_with_parentheses`. 

Other remark:

* As the stack only receives `(` characters, you don&#39;t actually need those characters (what else could it be?), but only the length. For that you can use a numeric variable, like `depth`. It would correspond to `len(stack)` without actually having the stack.

Here is a correction of your code:

def split_parentheses(input_string):
result = []
depth = 0 # Use this instead of a stack
current = "" # This variable will collect the string that will be a single entry in the result
for char in input_string:
if char in "()":
current += char # Collect all the parentheses
if char == '(':
depth += 1
elif char == ')':
depth -= 1
if depth < 0:
return "Invalid input string: parentheses not perfectly matched."
if depth == 0:
result.append(current)
current = "" # clear string for the next group
if depth:
return "Invalid input string: parentheses not perfectly matched."
return result

input_string = input("Enter a string of perfectly matched parentheses and whitespace: ")
result = split_parentheses(input_string)
print(result)



</details>



huangapple
  • 本文由 发表于 2023年2月23日 19:42:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75544343.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定