英文:
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 `''.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'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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论