这是我的代码:我想将字符串从“ 3 [b2 [ca]]”解码为“ bcacabcacabcaca”。但是我的结果是“ [[[”。有人可以帮我吗?
def decompression(text):
intStack = []
charStack = []
temp = ""
result = ""
for i in range(len(text)):
if text[i].isdigit():
times = 0
while text[i].isdigit():
times = times * 10 + int(text[i])
i += 1
i -= 1
intStack.append(times)
elif text[i] == ']':
temp = ""
times = 0
if len(intStack) > 0:
times = intStack[-1]
intStack.pop()
while len(charStack) > 0 and charStack[-1] != '[':
temp += charStack[-1]
charStack.pop()
if len(charStack) > 0 and charStack[-1] == '[':
charStack.pop()
for j in range(times):
result += temp
for j in range(len(result)):
charStack.append(result[j])
result = ""
elif text[i] == '[':
if text[i-1].isdigit():
charStack.append(text[i])
else:
charStack.append(text[i])
intStack.append(1)
else:
charStack.append(text[1])
while len(charStack) != 0:
result += charStack[-1]
charStack.pop()
return result
print(decompression("3[b2[ca]]"))
我一直都在回答错误,我已经对其进行了数次检查,并与其他在线编辑器进行了测试,但是这段代码有什么问题?我仍然无法弄清楚。
答案 0 :(得分:0)
最后的else语句中有一个小的错字。它说
System.AggregateException: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread.
---> Grpc.Core.RpcException: Status(StatusCode=Cancelled, Detail="Cancelled")
--- End of inner exception stack trace ---
---> (Inner Exception #0) Grpc.Core.RpcException: Status(StatusCode=Cancelled, Detail="Cancelled")<---
应该是
else:
charStack.append(text[1])
此外,您应该缩进函数中的所有内容,否则python将不知道它是函数的一部分。
else:
charStack.append(text[i])
答案 1 :(得分:0)
除了上述答案和注释之外,如果整数不是单个数字,则用于查找intStack的逻辑不起作用,我的意思是在示例输入3 [b2 [ca]]中,intStack为[3,2 ]很好,但是如果输入为33 [b22 [c6 [a]]],则intStack应该为[33,22,6],但这种情况下您的逻辑将失败。
尝试此操作以查找intStack:
intStack = [];
index=[];
for i in range(len(text)):
if i not in index:
if text[i].isdigit():
times="";
while text[i].isdigit():
times+=text[i]
index.append(i);
i+=1
intStack.append(int(times))
答案 2 :(得分:0)
虽然这不是最佳做法,但它可以起作用:
text = "3[b2[ca]]"
list = list(text)
try:
for i in range(len(list)*2):
if list[i] == '[':
list[i] = '*('
if list[i] == ']':
list[i] = ')'
if list[i].isalpha() and list[i+1].isdigit():
list.insert(i+1,"+")
if list[i].isalpha() and list[i+1].isalpha():
list.insert(i+1,"+")
if list[i].isalpha():
globals()[list[i]] = str(list[i])
except:
pass
print(list)
result = ''.join(list)
print(result)
print(eval(result))
基本上,它的作用是:
try: except: pass
内部,因此我们忽略了IndexError: list index out of range
错误; [...]
被*(...)
替换,在其中找到字母和数字,并添加{ {1}}签名,以及在其附近找到字母的位置; +
内置函数(https://docs.python.org/3/library/functions.html#globals),我们从列表中获取每个字母并将其声明为一个变量,该变量将其自身的字符串表示形式作为值; globals()
https://docs.python.org/3/library/functions.html#eval,我们得到的结果是:eval()