0

我有一个错误。我做了快速谷歌搜索,它对我没有帮助。

我添加了整个代码,很好的整个代码。来自用户的请求。

from derp_node import *

##############################################################################
# parse
############################################################################## 

def parse(tokens, i = 0):
    """parse: tuple(String) * int -> (Node, int)
    From an infix stream of tokens, and the current index into the
    token stream, construct and return the tree, as a collection of Nodes, 
    that represent the expression.

    NOTE:  YOU ARE NOT ALLOWED TO MUTATE 'tokens' (e.g. pop())!!!  YOU
        MUST USE 'i' TO GET THE CURRENT TOKEN OUT OF 'tokens'
    """
    if tokens == []:
        raise TypeError("Error: Empty List.")
    elif tokens[int(i)] == '*':
        tokens.remove(int(i))
        return mkMultiplyNode(parse(tokens), parse(tokens))
    elif tokens[int(i)] == '//':
        tokens.remove(int(i))
        return mkDivideNode(parse(tokens), parse(tokens))
    elif tokens[int(i)] == '+':
        tokens.remove(int(i))
        return mkAddNode(parse(tokens), parse(tokens))
    elif tokens[int(i)] == '-':
        tokens.remove(int(i))
        return mkSubtractNode(parse(tokens), parse(tokens))
    elif tokens[int(i)].isdigit():
        return mkLiteralNode(tokens.remove(int(i)))
    elif not tokens[int(i)].isdigit():
        return mkVariableNode(tokens.remove(int(i)))
    else:
        raise TypeError("Error: Invalid Input")

##############################################################################
# main
##############################################################################

def main():
    """main: None -> None
    The main program prompts for the symbol table file, and a prefix 
    expression.  It produces the infix expression, and the integer result of
    evaluating the expression"""

    print("Hello Herp, welcome to Derp v1.0 :)")

    inFile = input("Herp, enter symbol table file: ")
    symTbl = {}
    for line in open(inFile):
        i = line.split()
        symTbl[i[0]] = int(i[1])
    print("Derping the symbol table (variable name => integer value)...")
    for variable in sorted(symTbl):
        print(variable + " => " + str(symTbl[variable]))

    # STUDENT: CONSTRUCT AND DISPLAY THE SYMBOL TABLE HERE

    print("Herp, enter prefix expressions, e.g.: + 10 20 (RETURN to quit)...")

    # input loop prompts for prefix expressions and produces infix version
    # along with its evaluation
    while True:
        prefixExp = input("derp> ")
        if prefixExp == "":
            break

        # STUDENT: GENERATE A LIST OF TOKENS FROM THE PREFIX EXPRESSION
        prefixLst = prefixExp.split()
        # STUDENT: CALL parse WITH THE LIST OF TOKENS AND SAVE THE ROOT OF 
        # THE PARSE TREE.
        tokens = []
        parseLst = parse(prefixLst, tokens)
        # STUDENT: GENERATE THE INFIX EXPRESSION BY CALLING infix AND SAVING
        # THE STRING    
        infixLst = infix(parseLst)

        print("Derping the infix expression:")

        # STUDENT: EVALUTE THE PARSE TREE BY CALLING evaluate AND SAVING THE
        # INTEGER RESULT

        print("Derping the evaluation:")

    print("Goodbye Herp :(")

if __name__ == "__main__":
    main()

我收到的错误是:

  File "derpNew.py", line 31, in parse
    if tokens[int(i)] == '*':
TypeError: int() argument must be a string or a number, not 'list'

如果我从变量中删除 int() i,则会收到此错误:TypeError: list indices must be integers, not list

我想将列表转换为元组吗?任何帮助都会很棒。谢谢你。

如果你们好奇我是如何调用解析的。我把它放在主要功能下。

    tokens = []
    parseLst = parse(tokens, i)

编辑: 循环:

while True:
    prefixExp = input("derp> ")
    if prefixExp == "":
        break
    prefixLst = prefixExp.split()
    tokens = []
    parseLst = parse(tokens, i)
4

3 回答 3

1

parseLst = parse(tokens, i)- 除非你定义,否则这条线没有意义i。如果你想通过 default i=0,那么就把它排除在外:parseLst = parse(tokens).

编辑:粘贴整个代码后,i之前定义了一些(显然不相关),这就是没有 NameError 的原因。

于 2013-11-14T04:23:26.167 回答
0

传递的变量i是 a list,这就是错误的原因!需要有关正在传递的参数的更多信息以帮助您更多!

列表索引像这样工作

>>> my_list = [1, 2, 3, 4, 5]
>>> for index in range(5):
...    print my_list[i]
1
2
3 
4
5
>>> my_list[3]
4
于 2013-11-14T04:05:55.197 回答
0

您将什么parse(...)作为第二个参数传递给该方法?如果它是一个列表,它不应该。您可能想要更改您传递给的值parse

您可能还想tokens在 other 之前检查是否是一个空列表,ifs否则会导致另一个错误。

if tokens == []:
    raise TypeError("Error: Empty List.")
elif tokens[int(i)] == '*':
    tokens.remove(int(i))
    return mkMultiplyNode(parse(tokens), parse(tokens))
    return mkSubtractNode(parse(tokens), parse(tokens))
elif tokens[int(i)].isdigit():
    return mkLiteralNode(tokens.remove(int(i)))
elif not tokens[int(i)].isdigit():
    return mkVariableNode(tokens.remove(int(i)))
else:
    raise TypeError("Error: Invalid Input")
于 2013-11-14T04:07:57.847 回答