When I try a '=' operator to get python to compare the values of arguments to user input, it tells me it just doesn't work with a Syntax Error.
For whatever reason, changing all equal signs to the 'is' operator fixes this error. Though I feel like this is a good way to make my program incredibly buggy instead of a proper fix.
def movePieces1(initialSpot,finalSpot):
initialSpot = input('Move which piece?: ').upper()
finalSpot = input('To which place?: ').upper()
if initialSpot = 'A1' and finalSpot = row1[0] or row1[2,5]:
print('Invalid Move')
elif initialSpot = 'A2' and finalSpot = row1[1] or row1[3,5]:
print('Invalid Move')
Error:
File "pown-chess.py", line 81
if initialSpot = 'A1' and finalSpot = row1[0] or row1[2,5]:
^
SyntaxError: invalid syntax
To check for equality you need to use ==.
= assigns a name to a value.
Change it to something like this:
def movePieces1(initialSpot,finalSpot):
initialSpot = input('Move which piece?: ').upper()
finalSpot = input('To which place?: ').upper()
if initialSpot == 'A1' and finalSpot == row1[0] or row1[2,5]:
print('Invalid Move')
elif initialSpot == 'A2' and finalSpot == row1[1] or row1[3,5]:
print('Invalid Move')
Related
I need to make a language that has variables in it, but it also needs the letter 'd' to be an operand that has a number on the right and maybe a number on the left. I thought that making sure the lexer checks for the letter first would give it precedence, but that doesn't happen and i don't know why.
from ply import lex, yacc
tokens=['INT', 'D', 'PLUS', 'MINUS', 'LPAR', 'RPAR', 'BIGGEST', 'SMALLEST', 'EQ', 'NAME']
t_PLUS = r'\+'
t_MINUS = r'\-'
t_LPAR = r'\('
t_RPAR = r'\)'
t_BIGGEST = r'\!'
t_SMALLEST = r'\#'
t_D = r'[dD]'
t_EQ = r'\='
t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*'
def t_INT(t):
r'[0-9]\d*'
t.value = int(t.value)
return t
def t_newline(t):
r'\n+'
t.lexer.lineno += 1
t_ignore = ' \t'
def t_error(t):
print("Not recognized by the lexer:", t.value)
t.lexer.skip(1)
lexer = lex.lex()
while True:
try: s = input(">> ")
except EOFError: break
lexer.input(s)
while True:
t = lexer.token()
if not t: break
print(t)
If i write:
3d4
it outputs:
LexToken(INT,3,1,0)
LexToken(NAME,'d4',1,1)
and i don't know how to work around it.
Ply does not prioritize token variables by order of appearance; rather, it orders them in decreasing order by length (longest first). So your t_NAME pattern will come before t_D. This is explained in the Ply manual, along with a concrete example of how to handle reserved words (which may not apply in your case).
If I understand correctly, the letter d cannot be an identifier, and neither can d followed by a number. It is not entirely clear to me whether you expect d2e to be a plausible identifier, but for simplicity I'm assuming that the answer is "No", in which case you can easily restrict the t_NAME regular expression by requiring an initial d to be followed by another letter:
t_NAME = '([a-ce-zA-CE-Z_]|[dD][a-zA-Z_])[a-zA-Z0-9_]*'
If you wanted to allow d2e to be a name, then you could go with:
t_NAME = '([a-ce-zA-CE-Z_]|[dD][0-9]*[a-zA-Z_])[a-zA-Z0-9_]*'
How to have multiple OR operators in a single if statement? I tried this way but there's an error of:
Incompatible data types in expression or assignment.
I looked at documentation of length function and it is LENGTH ( {string | raw-expression | blob-field } [ , type ] )?
Here's the code:
DEFINE VARIABLE cMonth AS CHARACTER.
DEFINE VARIABLE cDay AS CHARACTER.
DEFINE VARIABLE cYear AS CHARACTER.
UPDATE cDateFromUser.
cDay = (SUBSTRING(cDateFromUser,1,2)).
cMonth = (SUBSTRING(cDateFromUser,3,2)).
cYear = (SUBSTRING(cDateFromUser,5,4)).
IF (LENGTH(cDay <> 2)) OR (LENGTH(cMonth <> 2)) OR (LENGTH(cYear <> 4)) THEN DO:
/*Code*/
END.
ELSE DO:
/*Code*/
END.
The syntax is not right here. Use the following IF:
IF (LENGTH(cDay) <> 2) OR (LENGTH(cMonth) <> 2) OR (LENGTH(cYear) <> 4) THEN DO:
Attempting to sort a list and then determine whether an user input is in list and I am continually getting an error in the recursive binary search.
def main():
list = ['Paul', 'Aaron', 'Jacob', 'James', 'Bill', 'Sara', 'Cathy',
'Barbara', 'Amy', 'Jill']
print("Unsorted list:")
print(list)
bubbleSort(list)
print("Sorted list:")
print(list)
binarySearch()
This is where I am sorting the list
def bubbleSort(list): #sorting of the list
firstUnsorted = 0
swapped = True
while firstUnsorted < len(list) and swapped:
index = len(list)-1
swapped = False
while index > firstUnsorted:
if list[index] < list[index-1]:
swap(list, index-1, index)
swapped = True
index = index-1
firstUnsorted = firstUnsorted + 1
def swap(list, index1, index2):
temp = list[index1]
list[index1] = list[index2]
list[index2] = temp
This is the second part of the recursive binary search and the section I am getting my error
def recursiveBSearch(names, target, first, last):
if first > last:
return False
else:
middle = int((first + last)/2)
if target == list[middle]: #this is where I am getting on my error
return True
else:
if target < list[middle]: #this is where I am getting the error
recursiveBSearch(first, middle-1)
else:
recursiveBSearch(middle + 1, last)
This is the first part of the recursive binary search
def binarySearch(): #first part of recursive binary search
names = [list]
aName = input("enter a name to be found: ")
first = 0
last = len(names)-1
if recursiveBSearch(names, aName, first, last):
print(aName, "was found")
else:
print(aName, "was not found")
On a simple grammar I am in the bad situation that one of my ParseActions is not called.
For me this is strange as parseActions of a base symbol ("logic_oper") and a derived symbol ("cmd_line") are called correctly. Just "pa_logic_cmd" is not called. You can see this on the output which is included at the end of the code.
As there is no exception on parsing the input string, I am assuming that the grammar is (basically) correct.
import io, sys
import pyparsing as pp
def diag(msg, t):
print("%s: %s" % (msg , str(t)) )
def pa_logic_oper(t): diag('logic_oper', t)
def pa_operand(t): diag('operand', t)
def pa_ident(t): diag('ident', t)
def pa_logic_cmd(t): diag('>>>>>> logic_cmd', t)
def pa_cmd_line(t): diag('cmd_line', t)
def make_grammar():
semi = pp.Literal(';')
ident = pp.Word(pp.alphas, pp.alphanums).setParseAction(pa_ident)
operand = (ident).setParseAction(pa_operand)
op_and = pp.Keyword('A')
op_or = pp.Keyword('O')
logic_oper = (( op_and | op_or) + pp.Optional(operand))
logic_oper.setParseAction(pa_logic_oper)
logic_cmd = logic_oper + pp.Suppress(semi)
logic_cmd.setParseAction(pa_logic_cmd)
cmd_line = (logic_cmd)
cmd_line.setParseAction(pa_cmd_line)
grammar = pp.OneOrMore(cmd_line) + pp.StringEnd()
return grammar
if __name__ == "__main__":
inp_str = '''
A param1;
O param2;
A ;
'''
grammar = make_grammar()
print( "pp-version:" + pp.__version__)
parse_res = grammar.parseString( inp_str )
'''USAGE/Output: python test_4.py
pp-version:2.0.3
operand: ['param1']
logic_oper: ['A', 'param1']
cmd_line: ['A', 'param1']
operand: ['param2']
logic_oper: ['O', 'param2']
cmd_line: ['O', 'param2']
logic_oper: ['A']
cmd_line: ['A']
'''
Can anybody give me a hint on this parseAction problem?
Thanks,
The problem is here:
cmd_line = (logic_cmd)
cmd_line.setParseAction(pa_cmd_line)
The first line assigns cmd_line to be the same expression as logic_cmd. You can verify by adding this line:
print("???", cmd_line is logic_cmd)
Then the second line calls setParseAction, which overwrites the parse action of logic_cmd, so the pa_logic_cmd will never get called.
Remove the second line, since you are already testing the calling of the parse action with pa_logic_cmd. You could change to using the addParseAction method instead, but to my mind that is an invalid test (adding 2 parse actions to the same pyparsing expression object).
Or, change the definition of cmd_line to:
cmd_line = pp.Group(logic_cmd)
Now you will have wrapped logic_cmd inside another expression, and you can then independently set and test the running of parse actions on the two different expressions.
Given I have a map like:
def myMap = [ b : [ c:"X" ] ]
And a string
def key = 'b.c'
I'd like to see my options for using the key to get to the value 'X'.
I have come up with two ways of achieving this myself, but I am not very happy with these solutions:
1) Eval.me("theMap", myMap, "theMap.$key")
2) mayMap."$key.split('\\.')[0]"."$key.split('\\.')[1]"
Anyone has a better way of doing this in Groovy?
A convenient way is to use ConfigObject which implements Map.
def myMap = [b:[c:'X', d: 'Y'], a:[n:[m:[x:'Y']]]] as ConfigObject
def props = myMap.toProperties()
assert props['b.c'] == 'X'
assert props.'b.c' == 'X'
assert props.'a.n.m.x' == 'Y'
Pros:
No more splitting.
No more evaluating.
IMHO its not the ConfigObject, that does the trick, its the Properties (from ConfigObject.toProperties()). Look & try:
def props = new ConfigSlurper().parse("""
b {
c = 'X'
d = 'Y'
}
a {
n {
m {
x:'Y'
}
}
}""")
assert props['b.c'] == 'X'
assert props.'b.c' == 'X'
assert props.'a.n.m.x' == 'Y'
'passed'
Assertion failed:
assert props['b.c'] == 'X'
| | |
| [:] false
[b:[c:X, d:Y], a:[n:[m:[:]]], b.c:[:]]
at ConsoleScript7.run(ConsoleScript7:14)
and I really wish, the ConfigObject could be indexed with such combined keys like above