Expression trees parsing and execution of operations - parsing

I got this problem in a coding challenge. I couldn't solve it on time but I still want to know how could it be done. I am not very familiar with expression trees and I found it hard to model the problem. The description goes like this:
Input: expression_tree | sequence_of_operations
The input is a single line of text with a expression tree and a sequence of operations separated by | character and ended by a \n newline character. Spaces are allowed in the input but should be ignored.
The expression tree is a sequence of 1-character variables A-Z and with sub expression trees formed by parenthesis (expression_tree). Examples: AB, A(B C D), (AB)C((DE)F)
The sequence of operations is a string of with characters R (reverse) or S (simplify)
Reverse means reverse the order of everything in expression tree. Applying reverse twice in a row cancels out.
Example: (AB)C((DE)F) | R should print (F(ED))C(BA)
Simplify means remove the parentheses around the very first element in the expression tree and each of its subexpression trees. Applying S multiple times should have same result as applying S once.
Example: (AB)C((DE)F) | S should print ABC(DEF)
Output: Read the expression tree and apply the sequence of operations from left to right to the expression tree, print out the result without characters.
What I would like to know the most is how to model the expression tree to handle the parentheses and how does the simplify operation should work?

'''
Examples are as follows :
INPUT:
(AB)(C(DE))/SS
(((AB)C)D)E/SS
(((AB)C)D)E/SR
(AB)C((DE)F)/SRS
(AB(CD((EF)G)H))(IJ)/SRS
(AB(CD((EF)G)H))(IJ)/SSSRRRS
(A(B(C)D)E(FGH(IJ)))/SRRSSRSSRRRSSRS
(A(BC(D(E((Z)K(L)))F))GH(IJK))/S
-------------------------------
OUTPUT:
AB(C(DE))
ABCDE
EDCBA
FEDCBA
JI(H(GFE)DC)BA
JI(H(GFE)DC)BA
JIHFGE(D(C)B)A
A(BC(D(E(ZK(L)))F))GH(IJK)/S
'''
'''
operationReverse function returns a reversed expression tree
Example : AB(CD) -> (DC)BA
'''
def operationReverse(expression):
'''============== Reversing the whole expressions ================'''
expression = expression[::-1]
expression = list(expression)
'''========= Replace Closing brace with Opening brace and vice versa ========='''
for x in range(0, len(expression)):
if(expression[x] != ')' and expression[x] != '('):
continue
elif(expression[x] == ")"):
expression[x] = "("
else:
expression[x] = ")"
expression = ''.join(expression)
return expression
'''
operationSimplify function returns a simplified expression tree
Example : (AB)(C(DE)) -> AB(C(DE))
operationSimplify uses recursion
'''
def operationSimplify(expression):
'''========= If no parenthesis found then return the expression as it is because it is already simplified ========='''
'''========= This is also the base condition to stop recursion ============='''
if(expression.find('(')==-1):
return expression
'''If 1st character is opening brace then find its correspoinding closing brace and remove them and call the function by passing the values between the opening and closing brace'''
if(expression[0] == '('):
x = 1
#numOfOpeningBrackets = maintains the count of opening brackets for finding it's corresponding closing bracket
numOfOpeningBrackets = 1
while(x < len(expression)):
if(expression[x] != ')' and expression[x] != '('):
x = x + 1
continue
elif(expression[x] == "("):
numOfOpeningBrackets = numOfOpeningBrackets + 1
x = x + 1
else:
numOfOpeningBrackets = numOfOpeningBrackets - 1
if(numOfOpeningBrackets == 0):
posOfCloseBracket = x
break
x = x + 1
expression = operationSimplify(expression[1:posOfCloseBracket]) + expression[posOfCloseBracket+1:]
'''========= If no parenthesis found then return the expression as it is because it is already simplified ========='''
if(expression.find('(')==-1):
return expression
'''========= Find the opening brace and it's closing brace and new expression tree will be concatenation of start of string till opening brace including the brace and string with in the opening brace and closing brace passed as an argument to the function itself and the remaining string ========='''
x = 0
#numOfOpeningBrackets = maintains the count of opening brackets for finding it's corresponding closing bracket
recursion = False
numOfOpeningBrackets = 0
while (x < len(expression)):
if(expression[x] != ')' and expression[x] != '('):
x = x + 1
elif(expression[x] == "("):
if(numOfOpeningBrackets == 0 or recursion == True):
numOfOpeningBrackets = 0
recursion = False
posOfStartBracket = x
y = x
numOfOpeningBrackets = numOfOpeningBrackets + 1
x = x + 1
else:
numOfOpeningBrackets = numOfOpeningBrackets - 1
if(numOfOpeningBrackets == 0):
posOfCloseBracket = x
x = y
expression=expression[0:posOfStartBracket+1]+operationSimplify(expression[posOfStartBracket+1:posOfCloseBracket])+expression[posOfCloseBracket:]
recursion = True
x = x + 1
return expression
'''
solution fucntion prints the final result
'''
def solution(inputString):
'''========= Remove the spaces from the input ==============='''
#inputString = inputString.replace("\n","")
inputString = inputString.replace(" ","")
inputString = inputString.replace("\t","")
#inputString = inputString.replace("()","")
'''=============== The substring before '/' is expression tree and substring after '/' is sequence of operations ======================'''
#posOfSlash = Position Of Slash Character
posOfSlash = inputString.find('/')
if(posOfSlash == -1):
print (inputString)
return
#expressionTree = Expression Tree
expressionTree = inputString[0:posOfSlash]
#seqOfOp = sequence of operations to be performed
seqOfOp = inputString[posOfSlash+1:]
'''============ If sequence Of Operations is empty then print the expression tree as it is ============== '''
if(len(seqOfOp)==0):
print(expressionTree)
return
'''============= Removing all the pairs of RR from the sequence Of Operations =================='''
seqOfOp = seqOfOp.replace(r+r,'')
'''============ All mulptiple S are replaced by one single S ================'''
while(seqOfOp.find(s+s) != -1):
seqOfOp = seqOfOp.replace(s+s,s)
'''============ If to perform operation R then call operationReverse() else if to perform operation S call operationSimplify() ================'''
for x in range (0 , len(seqOfOp)):
if(seqOfOp[x] == r):
expressionTree = operationReverse(expressionTree)
else :
expressionTree = operationSimplify(expressionTree)
print(expressionTree)
return
'''======= Global variables r and s representing operations R and S'''
r = 'R'
s = 'S'
while True:
try:
inputString = input()
'''==================== Calling function solution ======================'''
solution(inputString)
except EOFError:
break

Related

Assistance related to Lua programming where Basic Calculator need to build using 3 operators addition, subtraction and multiple

We had given below task
Create three function using Lua which can perform addition, subtraction and multiplication/
The program should be
Accept any number.
Check the operator + - *. If not the print "Invalid operand" and exit.
Accept two operands. if any operand not number print "Invalid operand" and exit. use - tonumber()
Perform the operation and print result.
We had written code as below which not working as expected , not sure where we went wrong, please guide us
local operators = {
["+"] = function(x,y) return x+y end,
["-"] = function(x,y) return x-y end,
["*"] = function(x,y) return x*y end
}
local function default()
print "Invalid operand"
end
local num1 = io.read()
local num2 = io.read()
local operator = io.read()
local func (
if operator == "+" then
local add = tonumber(num1) + tonumber(num2)
end
if operator == "-" then
local subtract = tonumber(num1) - tonumber(num2)
end
if operator == "*" then
local multiply = tonumber(num1) * tonumber(num2)
end
)
or default
print(func(num1,num2))
io.read()
Correct code is
local operators = {
["+"] = function (x, y) return x + y end,
["-"] = function (x, y) return x - y end,
["*"] = function (x, y) return x * y end,
}
local operator = operators[io.read()]
local num1 = tonumber(io.read())
local num2 = tonumber(io.read())
if num1 and num2 then
if operator then
print(operator(num1, num2))
else
print("Invalid operator")
end
else
print("Invalid operand")
end
Your code has syntax errors and doesn't make too much sense.
local func (
if operator == "+" then
local add = tonumber(num1) + tonumber(num2)
end
if operator == "-" then
local subtract = tonumber(num1) - tonumber(num2)
end
if operator == "*" then
local multiply = tonumber(num1) * tonumber(num2)
end
)
or default
To define a local function you can write
local myFunction = function() end
or
local function myFunction() end
But not
local func()
As you define the function it can never be nil. So short-circuiting a function definition like
local default = function() end
local myFunction = function() end or default
doesn't make sense.
You should add instructions so the user knows what to enter befor you call io.read().
This part of your code is not used at all:
local operators = {
["+"] = function(x,y) return x+y end,
["-"] = function(x,y) return x-y end,
["*"] = function(x,y) return x*y end
}
Also your function func does nothing but creating local variables which are not used.
The function does not return a value so printing it's return value like print(func(num1, num2)) won't print a result as intended.
You also fail to check if the user actually entered valid characters like numbers or operators. This will cause Lua errors if the user inputs something else.
Make use of the operators table. Instead of setting operator to the string that a user inputs, set it to the function that the user needs. If the user inputs an operator that is not in the table, operator will be set to nil:
local operator = operators[io.read()]
Similarly, set num1 and num2 directly to the numbers that will be operands instead of setting them to user input strings:
local num1 = tonumber(io.read())
local num2 = tonumber(io.read())
If tonumber can't convert the user inputs into numbers, num1 or num2 will be set to nil.
You can use the fact that invalid inputs are given nil values to validate the input. You don't really need the default() function to simply report that input is bad, and I did not use this in the final code below. If you did want to remove this reporting to functions you should probably at least distinguish between bad operands and bad operators:
local function bad_operand()
print("Invalid operand")
end
local function bad_operator()
print("Invalid operator")
end
Now you just need to check whether the arguments are valid, and whether the operator is valid, and if so perform the calculation. Here is the code:
local operators = {
["+"] = function (x, y) return x + y end,
["-"] = function (x, y) return x - y end,
["*"] = function (x, y) return x * y end,
}
local num1 = tonumber(io.read())
local num2 = tonumber(io.read())
local operator = operators[io.read()]
if num1 and num2 then
if operator then
print(operator(num1, num2))
else
print("Invalid operator")
end
else
print("Invalid operand")
end
Here are some sample runs:
~/code/lua/scratch $ lua calc.lua
3
4
-
-1
~/code/lua/scratch $ lua calc.lua
7
5
*
35
~/code/lua/scratch $ lua calc.lua
3
/
/
Invalid operand
~/code/lua/scratch $ lua calc.lua
3
4
/
Invalid operator
The nice thing about using the operators table is that we can now add operators to the table to extend the functionality of the program without making any other changes:
local operators = {
["+"] = function (x, y) return x + y end,
["-"] = function (x, y) return x - y end,
["*"] = function (x, y) return x * y end,
["/"] = function (x, y) return x / y end,
["//"] = function (x, y) return x // y end,
}
Testing the new operators:
~/code/lua/scratch $ lua calc.lua
3
4
/
0.75
~/code/lua/scratch $ lua calc.lua
7
3
//
2

This expression was expected to have type 'unit' but here has type ''a []'

The following code was an attempt at a recursive bubble sort in F#, where I received the error
"This expression was expected to have type 'unit' but here has type ''a []'"
for the middle three lines:
let swap i j (arr : 'a []) =
let tmp = arr.[i]
arr.[i] <- arr.[j]
arr.[j] <- tmp
let rec recursiveBubbleSort i j (sequence : 'a []) =
if i = sequence.Length then sequence //error
elif j = sequence.Length then recursiveBubbleSort (i+1) 0 sequence //error
elif sequence.[i] > sequence.[j] then swap i j sequence //error
recursiveBubbleSort i (j+1) sequence
This is really puzzling me, as all of the resources I have found haven't sufficiently explained or implied why this is actually occurring. Any help would be greatly appreaciated.
I think this is what you wanted to write:
let rec recursiveBubbleSort i j (sequence : 'a []) =
if i = sequence.Length then sequence
elif j = sequence.Length then recursiveBubbleSort (i+1) 0 sequence
else
if sequence.[i] > sequence.[j] then swap i j sequence |> ignore
recursiveBubbleSort i (j+1) sequence
So, the last elif you wrote has to be an else, within that else there is another if that checks whether to perform the swap or not.
All if .. then, including elif or not, must end with an else unless it's a unit expression (as the call to swap).
That's why you were getting that error.
Finally note that your comparison is inverted, you will sort the list in descending order.

f# finding the indexes of a string in a char array

Hey all i am new to F#
I am trying to find the starting indexes of all the occurrences of a string in a char array.
e.g.
char array ['a';'b';'b';'a';'b';'b';'b';'b';'b';'a';'b']
would return 0 and 3 and 9 if you were searching for the string "ab"
Here's a solution using recursive functions:
/// Wraps the recursive findMatches function defined inside, so that you don't have to seed it with the "internal" paramters
let findMatches chars str =
/// Returns whether or not the string matches the beginning of the character array
let rec isStartMatch chars (str: string) =
match chars with
| char :: rest when str.Length > 0 ->
char = str.[0] && (isStartMatch rest str.[1..(str.Length - 1)])
| _ -> str.Length = 0
/// The actual function here
let rec findMatches matchedIndices i chars str =
match chars with
| _ :: rest ->
if isStartMatch chars str
then findMatches (i :: matchedIndices) (i + 1) rest str
else findMatches matchedIndices (i + 1) rest str
| [] -> matchedIndices
findMatches [] 0 chars str
Not the most efficient as it iterates over characters twice if they're part of a match, but that's not really a big worry.
I don't want to do a complete example here, so here is the hint:
let rec match (l:char seq) i=
match seq.tryFindindex ... (*the part you have already done goes here*)with
|None -> []
|Some(t) ->i+t::(match (Seq.skip t l) (i+t)
Basically, we just repeatedly apply the Findindex until it stops matching.

Recursive descent parsing: high precedence unary operators

I've figured out how to implement binary operators with precedence, like this (pseudocode):
method plus
times()
while(consume(plus_t)) do
times()
end
end
method times
number()
while(consume(times_t))
number()
end
end
// plus() is the root operation
// omitted: number() consumes a number token
So when I parse 4 + 5 * 6 it would:
plus
multiply
number (4 consumed)
plus_t consumed
multiply
number (5 consumed)
times_t consumed
number (6 consumed)
However, when I try adding a minus method (prefix minusing like -4, not infix minusing like 4 - 5):
method minus
consume(minus_t)
plus()
end
It takes a very low precedence, so -4 + 5 becomes -(4 + 5) rather than (-4) + 5 and this is undesirable.
What can I do to make a high precedence unary operator?
You've not said where in the hierarchy you're adding the minus method, but it looks like you're adding it above plus and making it the root.
You need to put it at last if you want unary - to have a higher precedence than + and *.
In your pseudocode, something like this should work:
method times
minus()
while(consume(times_t))
minus()
end
end
method minus
if(consume(minus_t))
// next number should have a unary minus attached
number()
else
number()
end
end
I'm learning about parsers these days, so I wrote a complete parser based on your pseudocode, it's in LiveScript, but should be easy to follow.
Edit: Running example on jsfiddle.net - http://jsfiddle.net/Dogbert/7Pmwc/
parse = (string) ->
index = 0
is-digit = (d) -> '0' <= d <= '9'
plus = ->
str = times()
while consume "+"
str = "(+ #{str} #{times()})"
str
times = ->
str = unary-minus()
while consume "*"
str = "(* #{str} #{unary-minus()})"
str
unary-minus = ->
if consume "-"
"(- #{number()})"
else
number()
number = ->
if is-digit peek()
ret = peek()
advance()
while is-digit peek()
ret += peek()
advance()
ret
else
throw "expected number at index = #{index}, got #{peek()}"
peek = ->
string[index]
advance = ->
index++
consume = (what) ->
if peek() == what
advance()
true
plus()
console.log parse "4+5*6"
console.log parse "-4+5"
console.log parse "-4*-5+-4"
Output:
(+ 4 (* 5 6))
(+ (- 4) 5)
(+ (* (- 4) (- 5)) (- 4))
PS: you may want to look at Operator-precedence Parsers for parsing complex precedence/associativity relatively easily.

how to compute the number of total constraints in smtlib2 files in api

I used the Z3_ast fs = Z3_parse_smtlib2_file(ctx,arg[1],0,0,0,0,0,0) to read file.
Additionally to add into the solver utilized the expr F = to_expr(ctx,fs) and then s.add(F).
My question is how can I get the number of total constraints in each instance?
I also tried the F.num_args(), however, it is giving wrong size in some instances.
Are there any ways to compute the total constraints?
Using Goal.size() may do what you want, after you add F to some goal. Here's a link to the Python API description, I'm sure you can find the equivalent in the C/C++ API: http://research.microsoft.com/en-us/um/redmond/projects/z3/z3.html#Goal-size
An expr F represents an abstract syntax tree, so F.num_args() returns the number of (one-step) children that F has, which is probably why what you've been trying doesn't always work. For example, suppose F = a + b, then F.num_args() = 2. But also, if F = a + b*c, then F.num_args() = 2 as well, where the children would be a and b*c (assuming usual order of operations). Thus, to compute the number of constraints (in case your definition is different than what Goal.size() yields), you can use a recursive method that traverses the tree.
I've included an example below highlighting all of these (z3py link here: http://rise4fun.com/Z3Py/It5E ).
For instance, my definition of constraint (or rather the complexity of an expression in some sense) might be the number of leaves or the depth of the expression. You can get as detailed as you want with this, e.g., counting different types of operands to fit whatever your definition of constraint might be, since it's not totally clear from your question. For instance, you might define a constraint as the number of equalities and/or inequalities appearing in an expression. This would probably need to be modified to work for formulas with quantifiers, arrays, or uninterpreted functions. Also note that Z3 may simplify things automatically (e.g., 1 - 1 gets simplified to 0 in the example below).
a, b, c = Reals('a b c')
F = a + b
print F.num_args() # 2
F = a + b * c
print F.num_args() # 2
print F.children() # [a,b*c]
g = Goal()
g.add(F == 0)
print g.size() # number of constraints = 1
g.add(Or(F == 0, F == 1, F == 2, F == 3))
print g.size() # number of constraints = 2
print g
g.add(And(F == 0, F == 1, F == 2, F == 3))
print g.size() # number of constraints = 6
print g
def count_constraints(c,d,f):
print 'depth: ' + str(d) + ' expr: ' + str(f)
if f.num_args() == 0:
return c + 1
else:
d += 1
for a in f.children():
c += count_constraints(0, d, a)
return c
exp = a + b * c + a + c * c
print count_constraints(0,0,exp)
exp = And(a == b, b == c, a == 0, c == 0, b == 1 - 1)
print count_constraints(0,0,exp)
q, r, s = Bools('q r s')
exp = And(q, r, s)
print count_constraints(0,0,exp)

Resources