?求助,用List嵌套组成的栈。代码有处不明白!

heshang110 2007-10-24 10:44:30
[code=python]
def convert_parens(tokens):
stack = [[]]
for token in tokens:
if token == '( ': # push
sublist = []
stack[-1].append(sublist)
stack.append(sublist)
elif token == ') ': # pop
stack.pop()
else: # update top of stack ???
stack[-1].append(token)
return stack[0]
[/code=python]
代码的意图:联系使用list的嵌套。我们想当碰到一个不是小括号的字符时,就把它入栈,这个栈还可以保持嵌套的层次,也就是说,在栈顶的元素,位于更内层的嵌套中。比如,我们输入
>>> phrase = "( the cat ) ( sat ( on ( the mat ) ) )"
>>> print convert_parens(phrase.split())
程序运行后的结果是[['the', 'cat'], ['sat', ['on', ['the', 'mat']]]]

我的问题是出在标记了“???”的地方,也就是一个入栈操作。我从代码上看,是对list中的最后一个元素进行的追加操作,比如,碰到了‘the’,我认为追加后的站内应该是这样子的[[[]], ['the']],可是程序给出的结果是[[['the']], ['the']]。

我的问题是 为什么第一个嵌套list也加入了入栈的元素呢?
...全文
52 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
iambic 2007-10-25
  • 打赏
  • 举报
回复
不好意思,回错了。
iambic 2007-10-25
  • 打赏
  • 举报
回复
类似于 http://host/web.html#BOTTOM
google: html 锚
iambic 2007-10-25
  • 打赏
  • 举报
回复
那你记得把另外两张帖结了吧……
iambic 2007-10-24
  • 打赏
  • 举报
回复
唉,你格式化代码失败了啊。在发帖的输入框紧上方有几个按钮,有一个鼠标移上去会显示“插入源代码”。

或者手动加标签。

错误的写法:

[/code=python]

正确的写法:
[code=Python]

iambic 2007-10-24
  • 打赏
  • 举报
回复
汗,你前面不是发了两张贴子吗?怎么又另起一个?
我还是不知道这个convert_parens到底应该返回什么。我改了点东西之后,返回的是[[], []]。

def convert_parens(tokens):
stack = [[]]
for token in tokens:
if token == '(': # push
# sublist = []
# stack[-1].append(sublist)
# stack.append(sublist)
stack[-1].append([])
stack.append([])
elif token == ')': # pop
stack.pop()
else: # update top of stack
stack[-1].append(token)
print stack
return stack[0]
# return stack

phrase = "( the cat ) ( sat ( on ( the mat ) ) )"
print convert_parens(phrase.split())

heshang110 2007-10-24
  • 打赏
  • 举报
回复
非常非常感谢楼上对我的耐心指导。我只是在一本书的练习中看到这个栈,其实它没有什么具体的作用,或者意义。它就是让读者熟悉对于list的操作和嵌套的含义。您的修改提醒了我,我知道我想要的答案了,谢谢!

37,742

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧