The new forums will be named Coin Return (based on the most recent vote)! You can check on the status and timeline of the transition to the new forums here.
The Guiding Principles and New Rules document is now in effect.
I'm getting an error in the code our prof sent us to work on, and it isn't something we're supposed to have to touch:
def error(message) :
print message
It says the error is after "print message," and that's there's a problem with the syntax. If I remove this particular definition, it says there's a syntax error at the end of the next line, leading me to believe the problem might be with the code before it:
if isinstance(tree, str) : # a VAR ?
ans = tree
else : # list of form, [op, ...] where op in ("~","^","v")
if tree[0] == "~" :
ans = "~" + toString(tree[1])
elif tree[0] in ("v", "^") :
ans = "(" + toString(tree[1]) + " " + tree[0] + " " + toString(tree[2]) + ")"
else :
error("bad optree structure")
ans = "?"
return ans
Including the exact error message and indenting that code (and/or including all of the code if it's not extremely long) would be helpful. That being said there is some strange stuff in that code but it shouldn't cause any problems. Just...weird for being in Python.
Barrakketh on
Rollers are red, chargers are blue....omae wa mou shindeiru
Including the exact error message and indenting that code (and/or including all of the code if it's not extremely long) would be helpful. That being said there is some strange stuff in that code but it shouldn't cause any problems. Just...weird for being in Python.
It is indented, but me putting it in the spoiler decided to ruin that. No error code, just a pop-up box that says "invalid syntax"
edit:
Here's the whole program:
""""Trans.py translates a proposition written with AND,OR,NOT so that
all occurrences of AND are replaced by OR,NOT.
Input: a string whose grammatical structure is defined as follows:
EXPR ::= VAR | ( EXPR OP EXPR ) | ~ EXPR
OP is "^" or "v"
VAR is an alphabetic letter
Output: an operator tree built according to this structure:
optree ::= VAR | ["v", optree, optree ] | ["~", optree]
whose truth-table meaning is identical to the meaning
of the Input.
Algorithm:
1. read the Input string and scan it, that is, split it into
a list of its words. Call this the ``wordlist''.
(Example: "(P ^ ~Q)" is scanned into
wordlist = ["(", "P", "^", "~", "Q", ")"]
)
2. One by one, move the strings in the wordlist into variable
nextword and call parseEXPR, which organizes the strings
into its operator tree according to the grammar rule for EXPR.
(Example: the previous wordlist is parsed into this operator
tree:
optree = ["^", "P", ["~", "Q"]]
)
3. Next, replace each occurrence of ["^", t1, t2] in optree
by ["~", ["v", ["~", t1], ["~", t2]]]
(Example:
optree2 = ["~", ["v", ["~", "P"], ["~", ["~", "Q"]]]]
)
4. Finally, erase all double negations: ["~", ["~", t]]
is replaced by t
(Example:
optree3 = ["~", ["v", ["~", "P"], "Q"]]
5. The final result prints as "~(~P v Q)"
"""
"""
SAMPLE EXECUTION:
$ python Trans.py
Type proposition to translate: ( p ^ ( q ^ ~r ))
parsed input: ]]
which denotes (p ^ (q ^ ~r))
ands removed: , , ]]]]]]
which denotes ~(~p v ~~(~q v ~~r))
double negations removed: , , 'r']]]
which denotes ~(~p v (~q v r))
"""
##### SCANNING AND PARSING (this is typically a separate module): ################
EOF = "!" # a word that marks the end of the input words
nextword = "" # holds the next unread input word
wordlist = [] # holds remaining input words
# global invariant: nextword + wordlist == all remaining unread input words
def scan(text) :
"""scan splits apart the symbols/words in text into a list of words.
pre: text is a string holding a proposition
post: answer is a wordlist of the words and symbols within text
(spaces and newlines are removed)
returns: answer
"""
OPERATORS = ("(", ")", "^", "v", "~") # must be one-symbol operators
SPACES = (" ", "\n")
SEPARATORS = OPERATORS + SPACES
next = "" # the next symbol/word to be added to the answer list
answer = []
for letter in text:
# invariant: answer + next + letter equals all the words/symbols
# read so far from text with SPACES removed
# see if next is complete and should be appended to answer:
if letter in SEPARATORS and next != "" :
answer.append(next)
next = ""
if letter in OPERATORS :
answer.append(letter)
elif letter in SPACES :
pass # discard space
else : # build a word or numeral
next = next + letter
if next != "" :
answer.append(next)
return answer
def getNextword() :
"""moves the front word in wordlist to nextword.
If wordlist is empty, sets nextword = EOF
"""
global nextword, wordlist
if wordlist == [] :
nextword = EOF
else :
nextword = wordlist[0]
wordlist = wordlist[1:]
def parseEXPR() :
"""builds an EXPR operator tree from the words in nextword + wordlist,
where EXPR ::= VAR | ( EXPR OP EXPR ) | ~ EXPR
OP is "^" or "v"
VAR is an alphabetic letter
pre: global var nextword holds the next unread word
post: ans is an operator tree holding the expression that
was read starting from nextword.
returns: ans
"""
if nextword.isalpha() : # a VAR
ans = nextword
getNextword()
elif nextword == "(" : # ( EXPR op EXPR ) ?
getNextword()
tree1 = parseEXPR()
op = nextword
if op == "^" or op == "v" :
getNextword()
tree2 = parseEXPR()
if nextword == ")" :
ans = [op, tree1, tree2]
getNextword()
else :
error("missing )")
else :
error("missing operator")
elif nextword == "~" :
getNextword()
tree = parseEXPR()
ans = ["~", tree]
else :
error("illegal symbol to start an expression")
def toString(tree):
"""reformats tree as a linear string
pre: tree is an optree
post: ans is a string that holds the words within tree
returns: ans
"""
if isinstance(tree, str) : # a VAR ?
ans = tree
else : # list of form, [op, ...] where op in ("~","^","v")
if tree[0] == "~" :
ans = "~" + toString(tree[1])
elif tree[0] in ("v", "^") :
ans = "(" + toString(tree[1]) + " " + tree[0] + " " + toString(tree[2]) + ")"
else :
error("bad optree structure")
ans = "?"
return ans
def error(message) :
print message
###### THE TRANSLATION FUNCTIONS: ########################
def replaceAnd(tree) :
"""replaces all occurrences of ["^", t1, t2 ] within tree
by ["~', ["v", ["~", t1], ["~", t2]] ]
pre: tree is an operator tree
post: ans is a new tree that looks like tree with the replacements
returns: ans
"""
# write this function's body:
print "replaceAnd not yet implemented"
if isinstance(tree, str)
ans = tree
else(tree[0] == "^")
ans = ["~", ["v", ["~", replaceAnd[tree1]], ["~", replaceAnd[tree2]]]]
return ans
def removeNeg(tree):
"""replaces all occurrences of ["~", ["~", t]] by t within tree
pre: tree is an operator tree
post: ans is an operator tree that looks like tree but with
all double negations removed
returns: ans
"""
# write this function's body:
print "removeNeg not yet implemented"
ans = tree
return ans
#### MAIN starts here: ######################################
# this code can be placed in a main function; as it stands, it is
# executed immediately when this module is loaded:
inputtext = raw_input("Type proposition to translate: ")
wordlist = scan(inputtext) # holds the words from the inputtext
print "wordlist =", wordlist
print
getNextword() # moves the first word of wordlist into nextword
Including the exact error message and indenting that code (and/or including all of the code if it's not extremely long) would be helpful. That being said there is some strange stuff in that code but it shouldn't cause any problems. Just...weird for being in Python.
It is indented, but me putting it in the spoiler decided to ruin that. No error code, just a pop-up box that says "invalid syntax"
When you're pasting code put it in code tags. You can wrap that in a spoiler tag (which is usually what we do for length). For instance, your snippet from the first post:
#!/usr/bin/env python
if isinstance(tree, str) : # a VAR ?
ans = tree
else : # list of form, [op, ...] where op in ("~","^","v")
if tree[0] == "~" :
ans = "~" + toString(tree[1])
elif tree[0] in ("v", "^") :
ans = "(" + toString(tree[1]) + " " + tree[0] + " " + toString(tree[2]) + ")"
else :
error("bad optree structure")
ans = "?"
Obviously that won't run since tree isn't defined, but you get the point. Since Python cares about indentation it makes running samples a pain when it isn't preserved.
Barrakketh on
Rollers are red, chargers are blue....omae wa mou shindeiru
Edit: Whoops, fucked up the first time. Here we go.
""""Trans.py translates a proposition written with AND,OR,NOT so that
all occurrences of AND are replaced by OR,NOT.
Input: a string whose grammatical structure is defined as follows:
EXPR ::= VAR | ( EXPR OP EXPR ) | ~ EXPR
OP is "^" or "v"
VAR is an alphabetic letter
Output: an operator tree built according to this structure:
optree ::= VAR | ["v", optree, optree ] | ["~", optree]
whose truth-table meaning is identical to the meaning
of the Input.
Algorithm:
1. read the Input string and scan it, that is, split it into
a list of its words. Call this the ``wordlist''.
(Example: "(P ^ ~Q)" is scanned into
wordlist = ["(", "P", "^", "~", "Q", ")"]
)
2. One by one, move the strings in the wordlist into variable
nextword and call parseEXPR, which organizes the strings
into its operator tree according to the grammar rule for EXPR.
(Example: the previous wordlist is parsed into this operator
tree:
optree = ["^", "P", ["~", "Q"]]
)
3. Next, replace each occurrence of ["^", t1, t2] in optree
by ["~", ["v", ["~", t1], ["~", t2]]]
(Example:
optree2 = ["~", ["v", ["~", "P"], ["~", ["~", "Q"]]]]
)
4. Finally, erase all double negations: ["~", ["~", t]]
is replaced by t
(Example:
optree3 = ["~", ["v", ["~", "P"], "Q"]]
5. The final result prints as "~(~P v Q)"
"""
"""
SAMPLE EXECUTION:
$ python Trans.py
Type proposition to translate: ( p ^ ( q ^ ~r ))
parsed input: ['^', 'p', ['^', 'q', ['~', 'r']]]
which denotes (p ^ (q ^ ~r))
ands removed: ['~', ['v', ['~', 'p'], ['~', ['~', ['v', ['~', 'q'], ['~', ['~', 'r']]]]]]]
which denotes ~(~p v ~~(~q v ~~r))
double negations removed: ['~', ['v', ['~', 'p'], ['v', ['~', 'q'], 'r']]]
which denotes ~(~p v (~q v r))
"""
##### SCANNING AND PARSING (this is typically a separate module): ################
EOF = "!" # a word that marks the end of the input words
nextword = "" # holds the next unread input word
wordlist = [] # holds remaining input words
# global invariant: nextword + wordlist == all remaining unread input words
def scan(text) :
"""scan splits apart the symbols/words in text into a list of words.
pre: text is a string holding a proposition
post: answer is a wordlist of the words and symbols within text
(spaces and newlines are removed)
returns: answer
"""
OPERATORS = ("(", ")", "^", "v", "~") # must be one-symbol operators
SPACES = (" ", "\n")
SEPARATORS = OPERATORS + SPACES
next = "" # the next symbol/word to be added to the answer list
answer = []
for letter in text:
# invariant: answer + next + letter equals all the words/symbols
# read so far from text with SPACES removed
# see if next is complete and should be appended to answer:
if letter in SEPARATORS and next != "" :
answer.append(next)
next = ""
if letter in OPERATORS :
answer.append(letter)
elif letter in SPACES :
pass # discard space
else : # build a word or numeral
next = next + letter
if next != "" :
answer.append(next)
return answer
def getNextword() :
"""moves the front word in wordlist to nextword.
If wordlist is empty, sets nextword = EOF
"""
global nextword, wordlist
if wordlist == [] :
nextword = EOF
else :
nextword = wordlist[0]
wordlist = wordlist[1:]
def parseEXPR() :
"""builds an EXPR operator tree from the words in nextword + wordlist,
where EXPR ::= VAR | ( EXPR OP EXPR ) | ~ EXPR
OP is "^" or "v"
VAR is an alphabetic letter
pre: global var nextword holds the next unread word
post: ans is an operator tree holding the expression that
was read starting from nextword.
returns: ans
"""
if nextword.isalpha() : # a VAR
ans = nextword
getNextword()
elif nextword == "(" : # ( EXPR op EXPR ) ?
getNextword()
tree1 = parseEXPR()
op = nextword
if op == "^" or op == "v" :
getNextword()
tree2 = parseEXPR()
if nextword == ")" :
ans = [op, tree1, tree2]
getNextword()
else :
error("missing )")
else :
error("missing operator")
elif nextword == "~" :
getNextword()
tree = parseEXPR()
ans = ["~", tree]
else :
error("illegal symbol to start an expression")
return ans
###### TOSTRING (FORMATTING) FUNCTION: #############################
def toString(tree):
"""reformats tree as a linear string
pre: tree is an optree
post: ans is a string that holds the words within tree
returns: ans
"""
if isinstance(tree, str) : # a VAR ?
ans = tree
else : # list of form, [op, ...] where op in ("~","^","v")
if tree[0] == "~" :
ans = "~" + toString(tree[1])
elif tree[0] in ("v", "^") :
ans = "(" + toString(tree[1]) + " " + tree[0] + " " + toString(tree[2]) + ")"
else :
error("bad optree structure")
ans = "?"
return ans
def error(message) :
print message
###### THE TRANSLATION FUNCTIONS: ########################
def replaceAnd(tree) :
"""replaces all occurrences of ["^", t1, t2 ] within tree
by ["~', ["v", ["~", t1], ["~", t2]] ]
pre: tree is an operator tree
post: ans is a new tree that looks like tree with the replacements
returns: ans
"""
# write this function's body:
print "replaceAnd not yet implemented"
if isinstance(tree, str)
ans = tree
else(tree[0] == "^")
ans = ["~", ["v", ["~", replaceAnd[tree1]], ["~", replaceAnd[tree2]]]]
return ans
def removeNeg(tree):
"""replaces all occurrences of ["~", ["~", t]] by t within tree
pre: tree is an operator tree
post: ans is an operator tree that looks like tree but with
all double negations removed
returns: ans
"""
# write this function's body:
print "removeNeg not yet implemented"
ans = tree
return ans
#### MAIN starts here: ######################################
# this code can be placed in a main function; as it stands, it is
# executed immediately when this module is loaded:
inputtext = raw_input("Type proposition to translate: ")
wordlist = scan(inputtext) # holds the words from the inputtext
print "wordlist =", wordlist
print
getNextword() # moves the first word of wordlist into nextword
optree = parseEXPR()
print "parsed input:", optree
print "which denotes", toString(optree)
print
optree2 = replaceAnd(optree)
print "ands removed: ", optree2
print "which denotes", toString(optree2)
print
optree3 = removeNeg(optree2)
print "double negations removed:", optree3
print "which denotes", toString(optree3)
Thor1590 on
0
admanbunionize your workplaceSeattle, WARegistered Userregular
The replaceAnd function is missing a colon after an if statement and an else should be elif (also missing a colon). The changes I made to get it running are simple:
--- Trans.orig.py 2009-02-23 23:40:26.000000000 -0500
+++ Trans.py 2009-02-23 23:43:13.000000000 -0500
@@ -189,9 +189,9 @@
"""
# write this function's body:
print "replaceAnd not yet implemented"
- if isinstance(tree, str)
+ if isinstance(tree, str):
ans = tree
- else(tree[0] == "^")
+ elif(tree[0] == "^"):
ans = ["~", ["v", ["~", replaceAnd[tree1]], ["~", replaceAnd[tree2]]]]
return ans
Barrakketh on
Rollers are red, chargers are blue....omae wa mou shindeiru
Hmmm. The code looks fine, which leads me to believe the indentation is being mis-read. I would cut out everything from the error function on. Make sure it evaluates, then paste those functions back in, one-by-one, and make sure the indentation is consistent with the rest of the file.
Alright. Just tried this, exact same error.
I tried removing the error block (edit: and everything below it), and it will compile without that.
Hmmm. The code looks fine, which leads me to believe the indentation is being mis-read. I would cut out everything from the error function on. Make sure it evaluates, then paste those functions back in, one-by-one, and make sure the indentation is consistent with the rest of the file.
Alright. Just tried this, exact same error.
I tried removing the error block (edit: and everything below it), and it will compile without that.
Just a bump in case you missed it. Read the post above yours.
Barrakketh on
Rollers are red, chargers are blue....omae wa mou shindeiru
Hmmm. The code looks fine, which leads me to believe the indentation is being mis-read. I would cut out everything from the error function on. Make sure it evaluates, then paste those functions back in, one-by-one, and make sure the indentation is consistent with the rest of the file.
Alright. Just tried this, exact same error.
I tried removing the error block (edit: and everything below it), and it will compile without that.
Just a bump in case you missed it. Read the post above yours.
I got it after that, yeah. Fixed it, but same error above it.
Thor1590 on
0
admanbunionize your workplaceSeattle, WARegistered Userregular
edited February 2009
This is odd. The code runs fine on my machine as well, with the exception of the errors Barrakketh found. What are you using to edit and interpret?
Posts
It is indented, but me putting it in the spoiler decided to ruin that. No error code, just a pop-up box that says "invalid syntax"
edit:
Here's the whole program:
Edit edit: That's indented, I swear to god, but c+p didn't leave it that way.
When you're pasting code put it in code tags. You can wrap that in a spoiler tag (which is usually what we do for length). For instance, your snippet from the first post:
Obviously that won't run since tree isn't defined, but you get the point. Since Python cares about indentation it makes running samples a pain when it isn't preserved.
Alright. Just tried this, exact same error.
I tried removing the error block (edit: and everything below it), and it will compile without that.
Just a bump in case you missed it. Read the post above yours.
I got it after that, yeah. Fixed it, but same error above it.
IDLE.