"term not defined" or "invalid syntax"

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jonathanemil
    New Member
    • Jul 2007
    • 4

    "term not defined" or "invalid syntax"

    Hello,

    I am a 1st semester Computer Science student in a Python class. Our current assignment calls for us to read a list from a file, create a 2-dimensional list from the file, and check to see whether or not 2-dim list constitutes a "magic square" (i.e. all the rows, columns and diagonals equal each other when added). We are to create several definitions, and I have had no problem reading from the file, creating the list, and getting the sum of the first row. The next thing I need to do is sum up the other rows and see if they are equal to the first row. If not equal, I return a false and the function ends, if all are equal, I return a True. When I try to call another function (def sum(list, dimensions)) in my "areRowSumsEqua lToSum" function, I am getting a message telling me that the term "dimensions " is not defined, even though i use the same term in the "def sum(list, dimensions)" function. When I try to call sum(list, dimensions) in the definition name, I get an "invalid syntax" error.

    The list file looks like this, the first line is the dimensions of the "square", with the list following after a blank space.

    3

    8
    1
    6
    3
    5
    7
    4
    9
    2

    Here is my code, I appreciate any help, and I apologize if this is a mess. I'm pretty green still.

    [CODE=python]
    def main():
    import string
    value = True
    while value:
    try:
    userfile = raw_input("Ente r the file name where the list is located: ")
    infile = open(userfile, 'r')
    value = False
    except IOError:
    print "File not found"
    dimensions = eval(infile.rea dline())
    infile.readline ()
    list = construct2dimli st(infile, dimensions)
    print sum(list, dimensions)
    print areRowSumsEqual ToSum(list, sum(list, dimensions))

    def construct2dimli st(infile, dimensions):
    outerlist = []
    for i in range(dimension s):
    sublist = []
    for j in range(dimension s):
    sublist = sublist + [eval(infile.rea dline())]
    outerlist = outerlist + [sublist]
    return outerlist

    print construct2dimli st(infile, dimensions)
    infile.close

    def sum(list, dimensions):
    rowsum = 0
    for i in range(dimension s):
    rowsum = rowsum + list[0][i]
    return rowsum

    def areRowSumsEqual ToSum(list, sum(list, dimensions)):
    rowsums = 0
    for i in range(1, len(list)):
    for j in range(len(list) ):
    rowsums = rowsums + list[i][j]
    if(sum(list) != rowsums):
    return False
    return True

    main() [/CODE]

    Thanks!

    edit: i guess the indents don't show up here?
    Last edited by bartonc; Jul 17 '07, 12:01 AM. Reason: Added [CODE=python][/CODE] tags.
  • bartonc
    Recognized Expert Expert
    • Sep 2006
    • 6478

    #2
    I can't quote your code here due to a bug in the system, but this should help:
    Originally posted by jonathanemil
    edit: i guess the indents don't show up here?
    I've added what are called code tags. Instructions are on the right hand side while posting or replying.

    I've marked up your submission, but haven't tested any thing.
    I can't stress this enough: Comment everything. You'll like yourself much more in the long run and getting help from others becomes easier, as well.

    Have fun:[CODE=python]
    def construct2dimli st(infile, dimensions):
    """Build a 2D list using the open file and DIMENSION_TUPLE ????"""
    outerlist = []
    ## for i in range(dimension s):?????????
    for i in range(dimension s[0]):
    sublist = []
    ## for j in range(dimension s):???????
    for j in range(dimension s[1]):
    ## sublist = sublist + [eval(infile.rea dline())]
    sublist.append( eval(infile.rea dline()))
    ## outerlist = outerlist + [sublist]
    outerlist.appen d(sublist)
    return outerlist

    #### never executed ####
    print construct2dimli st(infile, dimensions)
    # don't close here, because in was not opened here, anyway
    infile.close

    #### Use python built-in function instead
    ##def sum(list, dimensions):
    ## rowsum = 0
    ## for i in range(dimension s):
    ## rowsum = rowsum + list[0][i]
    ## return rowsum

    def areRowSumsEqual ToSum(list, mustBeANameHere ):
    rowsums = 0
    ## for i in range(1, len(list)): ## Use the list elements instead of an index
    for subList in list[1:]: # Might as well slice off the one that was already summed
    # that's one way to do it
    ## for j in range(len(list) ):
    ## rowsums = rowsums + list[i][j]
    ## if mustBeANameHere != rowsums:
    ## return False
    if sum(subList) != mustBeANameHere
    return False
    return True


    def main():
    import string
    value = True
    while value:
    try:
    userfile = raw_input("Ente r the file name where the list is located: ")
    infile = open(userfile, 'r')
    value = False
    except IOError:
    print "File not found"
    #### STOP EXECUTION ###
    return

    dimensions = eval(infile.rea dline())
    infile.readline () # skip a line
    # I like doing this - pass the prepared file to the worker
    # but don't use python keywords like 'list', 'dict', etc for variable names (bad practice)
    ## list = construct2dimli st(infile, dimensions)
    a2DList = construct2dimli st(infile, dimensions) # dimensions is presumably a tuple
    infile.close

    # sum() takes a list, just tell it which part of the array that you want to sum
    ## theSum = sum(a2DList, dimensions)
    theSum = sum(a2DList[0])
    print areRowSumsEqual ToSum(list, theSum)

    if __name__ == "__main__": # this makes it possible to import this module into others
    main()[/CODE]

    Comment

    • jonathanemil
      New Member
      • Jul 2007
      • 4

      #3
      Thanks for the reply bartonc. I now get this error:

      Code:
      Traceback (most recent call last):
        File "/Users/jonathan/Documents/pythonboard2.py", line 67, in <module>
          main()
        File "/Users/jonathan/Documents/pythonboard2.py", line 59, in main
          a2DList = construct2dimlist(infile, dimensions) # dimensions is presumably a tuple
        File "/Users/jonathan/Documents/pythonboard2.py", line 5, in construct2dimlist
          for i in range(dimensions[0]):
      TypeError: 'int' object is unsubscriptable
      I was wondering if you could look at my original code and possibly explain why I would be getting an invalid syntax error when I write my definition as:

      def areRowSumsEqual ToSum(list, sum(list, dimensions)):

      Is it an illegal operation to have "list" in the parameters twice, in two different forms (if that makes sense at all)? As I mentioned before, if I leave out "dimensions ", I get an error telling me that sum has two parameters, and I have left out one, or that "dimensions " is not defined.

      Thanks again for the help!

      Hmmm...I don't think I "coded" my code correctly for the message board.

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        Originally posted by jonathanemil
        Hello,

        I am a 1st semester Computer Science student in a Python class. Our current assignment calls for us to read a list from a file, create a 2-dimensional list from the file, and check to see whether or not 2-dim list constitutes a "magic square" (i.e. all the rows, columns and diagonals equal each other when added). We are to create several definitions, and I have had no problem reading from the file, creating the list, and getting the sum of the first row. The next thing I need to do is sum up the other rows and see if they are equal to the first row. If not equal, I return a false and the function ends, if all are equal, I return a True. When I try to call another function (def sum(list, dimensions)) in my "areRowSumsEqua lToSum" function, I am getting a message telling me that the term "dimensions " is not defined, even though i use the same term in the "def sum(list, dimensions)" function. When I try to call sum(list, dimensions) in the definition name, I get an "invalid syntax" error.

        The list file looks like this, the first line is the dimensions of the "square", with the list following after a blank space.

        3

        8
        1
        6
        3
        5
        7
        4
        9
        2

        Here is my code, I appreciate any help, and I apologize if this is a mess. I'm pretty green still.

        [CODE=python]
        def main():
        import string
        value = True
        while value:
        try:
        userfile = raw_input("Ente r the file name where the list is located: ")
        infile = open(userfile, 'r')
        value = False
        except IOError:
        print "File not found"
        dimensions = eval(infile.rea dline())
        infile.readline ()
        list = construct2dimli st(infile, dimensions)
        print sum(list, dimensions)
        print areRowSumsEqual ToSum(list, sum(list, dimensions))

        def construct2dimli st(infile, dimensions):
        outerlist = []
        for i in range(dimension s):
        sublist = []
        for j in range(dimension s):
        sublist = sublist + [eval(infile.rea dline())]
        outerlist = outerlist + [sublist]
        return outerlist

        print construct2dimli st(infile, dimensions)
        infile.close

        def sum(list, dimensions):
        rowsum = 0
        for i in range(dimension s):
        rowsum = rowsum + list[0][i]
        return rowsum

        def areRowSumsEqual ToSum(list, sum(list, dimensions)):
        rowsums = 0
        for i in range(1, len(list)):
        for j in range(len(list) ):
        rowsums = rowsums + list[i][j]
        if(sum(list) != rowsums):
        return False
        return True

        main() [/CODE]

        Thanks!

        edit: i guess the indents don't show up here?
        I made a change to this code snippet of yours:
        [code=Python]lst = construct2dimli st(infile, dimensions)
        print sum(lst, dimensions)
        print areRowSumsEqual ToSum(lst, dimensions)[/code]

        You cannot call a function in an argument list. Another change:[code=Python]def areRowSumsEqual ToSum(lst, dimensions):
        rowsums = 0
        for i in range(1, len(lst)):
        for j in range(len(lst)) :
        rowsums = rowsums + lst[i][j]
        if(sum(lst, dimensions) != rowsums):
        return False
        return True[/code]

        See if your code will execute now.

        Comment

        • bartonc
          Recognized Expert Expert
          • Sep 2006
          • 6478

          #5
          Originally posted by jonathanemil
          Thanks for the reply bartonc. I now get this error:
          Code:
          Traceback (most recent call last):
            File "/Users/jonathan/Documents/pythonboard2.py", line 67, in <module>
              main()
            File "/Users/jonathan/Documents/pythonboard2.py", line 59, in main
              a2DList = construct2dimlist(infile, dimensions) # dimensions is presumably a tuple
            File "/Users/jonathan/Documents/pythonboard2.py", line 5, in construct2dimlist
              for i in range(dimensions[0]):
          TypeError: 'int' object is unsubscriptable
          Your variable is called "dimentions " with an "s" so I assumed a tuple like
          Code:
          dimensions = (5, 5)
          I see now that you assume a square array so take out the subscript "[0]" part.
          I was wondering if you could look at my original code and possibly explain why I would be getting an invalid syntax error when I write my definition as:
          Code:
          def areRowSumsEqualToSum(list, sum(list, dimensions)):
          Won't work because you must have a name in the argument list so that it may be referred to later in the function. The syntax would be allowed in the function call:
          Code:
          areRowSumsEqualToSum(list, sum(list, dimensions))
          but not the definition.

          Is it an illegal operation to have "list" in the parameters twice, in two different forms (if that makes sense at all)? As I mentioned before, if I leave out "dimensions ", I get an error telling me that sum has two parameters, and I have left out one, or that "dimensions " is not defined.

          Thanks again for the help!

          Hmmm...I don't think I "coded" my code correctly for the message board.
          Keep trying to get your latest code posted correctly. You have a full hour to get it right. Then it's no big deal for me to fix it after that.

          Comment

          • jonathanemil
            New Member
            • Jul 2007
            • 4

            #6
            bartonc,

            If I could just ask you one more question, you'll be free of me (at least for the rest of this evening). Thank you for your help so far. I have finished my program, however, I am still having a hard time getting my "sum" into each of the different functions in order to compare it with other column/row/diagonal sums. After I calculated the sum in a definition, I figured if I defined "sum" as that definition (sum = sum(list, dimensions)), I'd be able to call that in my other functions easily. It obviously isn't working the way I had hoped-when I print what I hope will be a comparison between "sum" and one of the computed values, they don't equal each other (and they should). In fact, when I try to print "sum" in the other functions, I see "function sum at 0x11132b0", instead of an integer.

            Is there any way to get that "sum" into my other definitions without major changes?

            Here is my (almost) final code:
            [CODE=python]
            #magicsquareche cker.py
            #This program creates a two-dimensional list of any dimension using
            #input from a user-created file. It then evaluates the 2D list to
            #determine whether or not it constitues a "Magic Square".

            def main():
            import string
            print "This program constructs a two-dimensional list from a"
            print "user-supplied file and checks to see whether the list constitutes"
            print "a 'magic square'."
            value = True
            while value:
            try:
            userfile = raw_input("Ente r the file name where the list is located: ")
            infile = open(userfile, 'r')
            value = False
            except IOError:
            print "File not found"
            dimensions = eval(infile.rea dline())
            infile.readline ()
            list = construct2dimli st(infile, dimensions)
            print list
            print areRowSumsEqual ToSum(list, sum)
            print areColumnSumsEq ualToSum(list, sum)
            print isDownDiagonalS umEqualToSum(li st, sum)
            print isUpDiagonalSum EqualToSum(list , sum)
            print isMagicSquare(l ist)

            def construct2dimli st(infile, dimensions):
            outerlist = []
            for i in range(dimension s):
            sublist = []
            for j in range(dimension s):
            sublist = sublist + [eval(infile.rea dline())]
            outerlist = outerlist + [sublist]
            return outerlist
            construct2dimli st(infile, dimensions)
            print areRowSumsEqual ToSum(list, sum)
            infile.close

            def sum(list, dimensions):
            rowsum = 0
            for i in range(dimension s):
            rowsum = rowsum + list[0][i]
            return rowsum

            sum = sum(list, dimensions)

            def areRowSumsEqual ToSum(list, sum):
            otherrowsums = 0
            for i in range(1, len(list)):
            for j in range(len(list) ):
            otherrowsums = otherrowsums + list[i][j]
            if(sum != otherrowsums):
            return False
            return True

            def areColumnSumsEq ualToSum(list, sum):
            columnsums = 0
            for i in range(len(list) ):
            for j in range(len(list) ):
            columnsums = columnsums + list[j][i]
            if(sum != columnsums):
            return False
            return True

            def isDownDiagonalS umEqualToSum(li st, sum):
            downdiagonalsum = 0
            for i in range(len(list) ):
            downdiagonalsum = downdiagonalsum + list[i][i]
            if(sum != downdiagonalsum ):
            return False
            return True

            def isUpDiagonalSum EqualToSum(list , sum):
            updiagonalsum = 0
            for i in range((len(list ))-1, -1, -1):
            updiagonalsum = updiagonalsum + list[i][((len(list))-1)-i]
            if(sum != updiagonalsum):
            return False
            return True

            def isMagicSquare(l ist):
            if(areRowSumsEq ualToSum(list, sum) and areColumnSumsEq ualToSum(list, sum) and isDownDiagonalS umEqualToSum(li st, sum) and isUpDiagonalSum EqualToSum(list , sum)):
            return "Yes, the two-dimensional list is a magic square"
            return "No, the list does not constitute a magic square."

            main()[/CODE]

            One more thing, where do I select "Python Code"?

            Thanks again!

            Jon
            Last edited by bartonc; Jul 17 '07, 03:49 AM. Reason: Added [CODE=python][/CODE] tags.

            Comment

            • bartonc
              Recognized Expert Expert
              • Sep 2006
              • 6478

              #7
              I have to admit being a little disappointed when I saw that you had not made some of the changes that I had suggested. I tried, here, to keep as much of your work as possible, but I can't in good conscience let you create lists by adding them together. I have used list.append() as it should be used.

              As for code tag syntax, see the reason for edit at the bottom of your post. The thing is that, if I type it here, it won't show up. You can alway see the raw text of a post when you reply to it, though.[CODE=python]
              #magicsquareche cker.py
              #This program creates a two-dimensional list of any dimension using
              #input from a user-created file. It then evaluates the 2D list to
              #determine whether or not it constitues a "Magic Square".

              def construct2dimli st(infile, dimensions):
              outerlist = []
              for i in range(dimension s):
              sublist = []
              for j in range(dimension s):
              sublist.append( eval(infile.rea dline()))
              ## sublist = sublist + [eval(infile.rea dline())]
              outerlist.appen d(sublist)
              ## outerlist = outerlist + [sublist]
              return outerlist

              ## never executed due to the return above
              construct2dimli st(infile, dimensions)
              print areRowSumsEqual ToSum(list, sum) # It's bad practice to use built-in names as argument names
              infile.close

              def my_sum(aList, rowNum): # don't use built-in names for your function names
              """Return the some of a given row"""
              ## rowsum = 0
              ## for i in range(dimension s):
              ## rowsum = rowsum + aList[0][i]
              ## return rowsum
              return sum(aList[rowNum]) # call built-in sum()

              ## never executed due to the return above
              ## sum = my_sum(aList, dimensions)

              def sum_all(aList):
              """Return the total of all rows in the array"""
              return sum([sum(item) for item in aList]) # List comprehentions are very handy

              def areRowSumsEqual ToSum(aList, total):
              otherrowsums = 0
              for i in range(1, len(aList)):
              for j in range(len(aList )):
              otherrowsums = otherrowsums + aList[i][j]
              if(total != otherrowsums):
              return False
              return True

              def areColumnSumsEq ualToSum(aList, total):
              columnsums = 0
              for i in range(len(aList )):
              for j in range(len(aList )):
              columnsums = columnsums + aList[j][i]
              if(total != columnsums):
              return False
              return True

              def isDownDiagonalS umEqualToSum(aL ist, total):
              downdiagonalsum = 0
              for i in range(len(aList )):
              downdiagonalsum = downdiagonalsum + aList[i][i]
              if(total != downdiagonalsum ):
              return False
              return True

              def isUpDiagonalSum EqualToSum(aLis t, total):
              updiagonalsum = 0
              for i in range((len(aLis t))-1, -1, -1):
              updiagonalsum = updiagonalsum + aList[i][((len(aList))-1)-i]
              if(total != updiagonalsum):
              return False
              return True

              def isMagicSquare(a List):
              if(areRowSumsEq ualToSum(aList, total) and \
              areColumnSumsEq ualToSum(aList, total) and \
              isDownDiagonalS umEqualToSum(aL ist, total) and \
              isUpDiagonalSum EqualToSum(aLis t, total)):
              return "Yes, the two-dimensional list is a magic square"
              return "No, the list does not constitute a magic square."

              def main():
              # don't import string unless you really need some constant defined there
              ## import string
              print "This program constructs a two-dimensional list from a"
              print "user-supplied file and checks to see whether the list constitutes"
              print "a 'magic square'."
              value = True
              while value:
              try:
              userfile = raw_input("Ente r the file name where the list is located: ")
              infile = open(userfile, 'r')
              value = False
              except IOError:
              print "File not found"
              dimensions = eval(infile.rea dline()) # An iteger defining BOTH dimensions
              infile.readline () # Skip a line
              a2DList = construct2dimli st(infile, dimensions)
              ### close the file here! ###
              infile.close

              print a2DList
              ## Caluculate the sum of the zeroth row ##
              rowZeroSum = my_sum(a2DList, 0)
              print areRowSumsEqual ToSum(a2DList, rowZeroSum)
              print areColumnSumsEq ualToSum(a2DLis t, rowZeroSum)
              print isDownDiagonalS umEqualToSum(a2 DList, rowZeroSum)
              print isUpDiagonalSum EqualToSum(a2DL ist, rowZeroSum)
              print isMagicSquare(a 2DList)


              if __name__ == "__main__":

              ## # used for testing without a file
              ## from random import randint
              ## size = 5 # the size of each side of the array
              ## a2DList = [[randint(0, 50) for i in range(size)] for j in range(size)]

              main()[/CODE]

              Comment

              • bartonc
                Recognized Expert Expert
                • Sep 2006
                • 6478

                #8
                You may ask all the questions that you like. That's what the Python Forum is here for.
                Code:
                In fact, when I try to print "sum" in the other functions, I see "function sum at 0x11132b0", instead of an integer.
                I think that I can put that into terms that are understandable:[CODE=python]
                >>> def aFunction(): # everything in python is an object of some sort
                ... return "hello world" # a function object returns an object of some sort
                ...
                >>> # when you use this syntax:
                >>> result = aFunction() # you call the function object and work gets done
                >>> print result
                hello world
                >>> result = aFunction # if you do this by mistake (or in your case not keeping names clear)
                >>> print result # you get the function object itself. not the result of the function call
                <function aFunction at 0x02F21C30>
                >>> [/CODE]

                Comment

                • bvdet
                  Recognized Expert Specialist
                  • Oct 2006
                  • 2851

                  #9
                  Originally posted by bartonc
                  You may ask all the questions that you like. That's what the Python Forum is here for.
                  Code:
                  In fact, when I try to print "sum" in the other functions, I see "function sum at 0x11132b0", instead of an integer.
                  I think that I can put that into terms that are understandable:[CODE=python]
                  >>> def aFunction(): # everything in python is an object of some sort
                  ... return "hello world" # a function object returns an object of some sort
                  ...
                  >>> # when you use this syntax:
                  >>> result = aFunction() # you call the function object and work gets done
                  >>> print result
                  hello world
                  >>> result = aFunction # if you do this by mistake (or in your case not keeping names clear)
                  >>> print result # you get the function object itself. not the result of the function call
                  <function aFunction at 0x02F21C30>
                  >>> [/CODE]
                  You have done some good work on this thread Barton. I have taken a slightly different approach to this problem. Pass the list to a function. In the function, initialize a set, sum each row, sum each column, sum the two diagonals, and add the results to the set. If the set length is greater than 1, the list is not a magic square and returns False:
                  Code:
                  def areAllSumsEqual(a2DList):
                      sumSet = set()
                      # sum each row
                      for row in a2DList:
                          sumSet.add(sum(row))
                          
                      # sum each column
                      for i in range(len(a2DList)):
                          sumSet.add(sum([row[i] for row in a2DList]))
                          
                      # sum diagonals
                      sumSet.add(sum([a2DList[i][i] for i in range(len(a2DList))]))
                      indxList = (range(len(a2DList)-1,-1,-1), range(len(a2DList)))
                      sumSet.add(sum([a2DList[indxList[0][i]][indxList[1][i]] for i in range(len(a2DList))]))
                      
                      if len(sumSet) > 1:
                          return False
                      return True

                  Comment

                  • jonathanemil
                    New Member
                    • Jul 2007
                    • 4

                    #10
                    Originally posted by bartonc
                    I have to admit being a little disappointed when I saw that you had not made some of the changes that I had suggested. I tried, here, to keep as much of your work as possible, but I can't in good conscience let you create lists by adding them together. I have used list.append() as it should be used.
                    The thing is, I'm at a point very early in the game, and some of the changes you made we haven't learned about yet in class. Also, we have very strict assignment specs, what you see in my code is the way my instructor INSISTS on things being done. So while my instructor encouraged us to ask around when we get stuck, I wouldn't feel right about copying portions of your code without really understanding them, and probably wouldn't have gotten credit for them.

                    But I really do appreciate the input, thank you.

                    Comment

                    • bartonc
                      Recognized Expert Expert
                      • Sep 2006
                      • 6478

                      #11
                      Originally posted by jonathanemil
                      The thing is, I'm at a point very early in the game, and some of the changes you made we haven't learned about yet in class. Also, we have very strict assignment specs, what you see in my code is the way my instructor INSISTS on things being done. So while my instructor encouraged us to ask around when we get stuck, I wouldn't feel right about copying portions of your code without really understanding them, and probably wouldn't have gotten credit for them.

                      But I really do appreciate the input, thank you.
                      Fair enough. I'll go ahead and stick in "best practices" when I see that your instructor is leading you astray (IMO), but won't expect to see them implemented in your re-posts.

                      Most of all, HAVE FUN WITH PYTHON! It's a really great language.

                      Comment

                      Working...