Converting Prefix expression to Infix Expression

Hi!
I need a little algorithm to convert a Prefix expression to an Infix expression. If I give the String
AND(OR(sunday;saturday);OR(coffee;milk))
the algorithm shoud give an expression of the form
(sunday OR saturday) AND (coffee OR milk).
Can somebody help?

school assignment? I wasn't fond of this one either
I don't want to give it all away, but the gist of this is that an arithmetic expression can be represented as a tree
+
| \
a b
To do prefix, input is "read node, get subnode 1, get subnode 2"
output is "out node, out subnode1, outsubnode2"
infix input is "read subnode1, read node, read subnode2"
output is the same sort of thing
You've got to implement that

Similar Messages

  • Using a Switch statement for Infix to Prefix Expressions

    I am stuck on the numeric and operator portion of the switch statement...I have the problem also figured out in an if/else if statement and it works fine, but the requirements were for the following algorithm:
    while not end of expression
    switch next token of expression
    case space:
    case left parenthesis:
    skip it
    case numeric:
    push the string onto the stack of operands
    case operator:
    push the operator onto the stack of operators
    case right parenthesis:
    pop two operands from operand stack
    pop one operator from operator stack
    form a string onto operand stack
    push the string onto operand stack
    pop the final result off the operand stack
    I know that typically case/switch statement's can only be done via char and int's. As I said I am stuck and hoping to get some pointers. This is for a homework assignment but I am really hoping for a few pointers. I am using a linked stack class as that was also the requirements. Here is the code that I have:
       import java.io.*;
       import java.util.*;
       import java.lang.*;
    /*--------------------------- PUBLIC CLASS INFIXTOPREFIX --------------------------------------*/
    /*-------------------------- INFIX TO PREFIX EXPRESSIONS --------------------------------------*/
        public class infixToPrefix {
          private static LinkedStack operators = new LinkedStack();
          private static LinkedStack operands = new LinkedStack();
            // Class variable for keyboard input
          private static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
             // Repeatedly reads in infix expressions and evaluates them
           public static void main(String[] args) throws IOException {
          // variables
             String expression, response = "y";
          // obtain input of infix expression from user
             while (response.charAt(0) == 'y') {
                System.out.println("Enter a parenthesized infix expression.");          // prompt the user
                System.out.println("Example: ( ( 13 + 2 ) * ( 10 + ( 8 / 3 ) ) )");
                System.out.print("Or as: ((13+2)*(10+(8/3))):  ");
                expression = stdin.readLine();     // read input from the user
             // output prefix expression and ask user if they would like to continue          
                System.out.println("The Prefix expression is: " + prefix(expression));     // output expression
                System.out.println("Evaluate another? y or n: ");          // check with user for anymore expressions
                response = stdin.readLine();     // read input from user
                if (response.charAt(0) == 'n') {          // is user chooses n, output the statement
                   System.out.println("Thank you and have a great day!");
                }     // end if statement
             }     // end while statement
          }     // end method main
       /*------------- CONVERSION OF AN INFIX EXPRESSION TO A PREFIX EXPRESSION ------------*/ 
       /*--------------------------- USING A SWITCH STATEMENT ------------------------------*/
           private static String prefix(String expression) {
                // variables
             String symbol, operandA, operandB, operator, stringA, outcome;
               // initialize tokenizer
             StringTokenizer tokenizer = new StringTokenizer(expression, " +-*/() ", true);     
             while (tokenizer.hasMoreTokens()) {
                symbol = tokenizer.nextToken();     // initialize symbol     
                switch (expression) {
                   case ' ':
                      break;     // accounting for spaces
                   case '(':
                      break;     // skipping the left parenthesis
                   case (Character.isDigit(symbol.charAt(0))):      // case numeric
                      operands.push(symbol);                                   // push the string onto the stack of operands
                      break;
                   case (!symbol.equals(" ") && !symbol.equals("(")):     // case operator
                      operators.push(symbol);                                             // push the operator onto the stack of operators
                      break;
                   case ')':
                      operandA = (String)operands.pop();     // pop off first operand
                      operandB = (String)operands.pop();     // pop off second operand
                      operator = (String)operators.pop();     // pop off operator
                      stringA = operator + " " + operandB + " " + operandA;          // form the new string
                      operands.push(stringA);
                      break;
                }     // end switch statement
             }     // end while statement
             outcome = (String)operands.pop();     // pop off the outcome
             return outcome;     // return outcome
          }     // end method prefix
       }     // end class infixToPrefixAny help would be greatly appreciated!

    so, i did what flounder suggested:
             char e = expression.charAt(0);
             while (tokenizer.hasMoreTokens()) {
                symbol = tokenizer.nextToken();     // initialize symbol     
                switch (e) {
                   case ' ':
                      break;     // accounting for spaces
                   case '(':
                      break;     // skipping the left parenthesis
                   case '0':
                   case '1':
                   case '2':
                   case '3':
                   case '4':
                   case '5':
                   case '6':
                   case '7':
                   case '8':
                   case '9':
                      operands.push(symbol);     // push the string onto the stack of operands
                      break;                               // case numeric
                   case '+':
                   case '-':
                   case '*':
                   case '/':
                      operators.push(symbol);     // push the operator onto the stack of operators
                      break;                               // case operator
                   case ')':
                      operandA = (String)operands.pop();     // pop off first operand
                      operandB = (String)operands.pop();     // pop off second operand
                      operator = (String)operators.pop();     // pop off operator
                      stringA = operator + " " + operandB + " " + operandA;          // form the new string
                      operands.push(stringA);
                      break;
                   default:
                }     // end switch statement
             }     // end while statement
             outcome = (String)operands.pop();     // pop off the outcome
             return outcome;     // return outcomeafter this, I am able to compile the code free of errors and I am able to enter the infix expression, however, the moment enter is hit it provides the following errors:
    Exception in thread "main" java.lang.NullPointerException
         at LinkedStack$Node.access$100(LinkedStack.java:11)
         at LinkedStack.pop(LinkedStack.java:44)
         at infixToPrefix.prefix(infixToPrefix.java:119)
         at infixToPrefix.main(infixToPrefix.java:59)
    Any ideas as to why? I am still looking through seeing if I can't figure it out, but any suggestions? Here is the linked stack code:
        public class LinkedStack {
       /*--------------- LINKED LIST NODE ---------------*/
           private class Node {
             private Object data;
             private Node previous;
          }     // end class node
       /*--------------  VARIABLES --------------*/
          private Node top;
      /*-- Push Method: pushes object onto LinkedStack --*/     
           public void push(Object data) {
             Node newTop = new Node();
             newTop.data = data;
             newTop.previous = top;
             top = newTop;
          }     // end function push
       /*--- Pop Method: pop obejct off of LinkedStack ---*/
           public Object pop()      {
             Object data = top.data;
             top = top.previous;
             return data;
          }     // end function pop
       } // end class linked stackEdited by: drmsndrgns on Mar 12, 2008 8:10 AM
    Edited by: drmsndrgns on Mar 12, 2008 8:14 AM
    Edited by: drmsndrgns on Mar 12, 2008 8:26 AM

  • How do I convert a Expression Web template into Dreamweaver CC?

    Just got the Adobe CC subscription they said I could convert an Expression Web site template to Dreamweaver?  It has a file master.dwt that has the common header, footer and menu

    Thanks, Dick - that helps. Save this code into the Templates folder at the root of the site. Name the saved file with a *.dwt extension. Let me know when you've done that and I'll tell you what to do next.
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html dir="ltr" xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta name="google-site-verification" content="n0PVQVe6Cs8EI5p0bjR5h5NxRpxwYuGqalb63SvPRaI" />
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
    <!-- TemplateBeginEditable name="doctitle" -->
    <title>Hotchkiss Sheep Camp  Stock Dog Trials </title>
        <meta name="description" content="Home page for the Hotchkiss Sheep Camp  Stock Dog Trials held in Hotchkiss Colorado on Mother's Day weekend in May"/>
        <meta name="keywords" content="Hotchkiss Sheep Camp, Stock Dog Trials, Hotchkiss, Colorado, SheepWagon, Sheep, herding dog,  Border Collie"/>
    <!-- TemplateEndEditable -->
    <link href="styles/style2.css" media="screen" rel="stylesheet" title="CSS" type="text/css" />
    <link rel="stylesheet" href="cssmenutools/scripts/MTHM1.css" type="text/css" />
    <style type="text/css">
    .auto-style1 {
      margin: 10px;
    .auto-style3 {
      vertical-align: middle;
    </style>
    <!-- TemplateBeginEditable name="head" -->
    <!-- TemplateEndEditable -->
    </head>
    <body style="width: 98%; background-color: #FFFFFF;">
    <form id="form1" runat="server">
        <!-- Begin Container --><div id="container" style="left: 10px; top: 1px; background-color: #FFFFFF;">
      <!-- Begin Masthead -->
      <!-- End Masthead -->
      <!-- Begin Navigation -->
        <div id="masthead" style="border-bottom-color: #E1F3FB; border-color: #BCE1FC; height: 162px; background-color: #BCE1FC; border-left-color: #BCE1FC; border-top-color: #BCE1FC; border-right-color: #BCE1FC;">
      <img alt="Hotchkiss Sheep Camp" height="75" src="images/Hotchkiss%20Logo.jpg" width="294" class="auto-style1" />
      <object type="application/x-shockwave-flash" data="HotchkissSheepCamp2.swf" width="358" height="159" align="right"><param name="movie"
      value="HotchkissSheepCamp2.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /><param name="play"
      value="true" /><param name="loop" value="true" /><param name="wmode" value="window" /><param name="scale" value="showall" />
      <param name="menu" value="true" /><param name="devicefont" value="false" /><param name="salign" value="" /><param name="allowScriptAccess"
      value="sameDomain" /><!--<![endif]-->
      <a href="http://www.adobe.com/go/getflash">
      <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" width="358" height="159" />
      </a>
      <!--[if !IE]-->
      </object>
       <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="358" height="159" id="HotchkissSheepCamp2" align="right">
      <param name="movie" value="HotchkissSheepCamp2.swf" />
      <param name="quality" value="high" />
      <param name="bgcolor" value="#ffffff" />
      <param name="play" value="true" />
      <param name="loop" value="true" />
      <param name="wmode" value="window" />
      <param name="scale" value="showall" />
      <param name="menu" value="true" />
      <param name="devicefont" value="false" />
      <param name="salign" value="" />
      <param name="allowScriptAccess" value="sameDomain" />
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
      </object>
         </div>
      <div id="MTHMWUHHfGCDiv" class="MTHMWUHHfGCwrapper"><div id="MTHMWUHHfGCTop" class="MTHMWUHHfGCtop"><div class="MTHMWUHHfGCtopmiddle"><ul><li class="MTHMWUHHfGCitem1" style="margin-left:0px"><a href="index.html"><span>Home</span></a></li><li class="MTHMWUHHfGCitem2"><a href="#"><span>We Are</span></a></li><li class="MTHMWUHHfGCitem2"><a href="#"><span>Handler's Area</span></a></li><li class="MTHMWUHHfGCitem2"><a href="#"><span>General Information</span></a></li><li class="MTHMWUHHfGCitem2"><a href="#"><span>Trials Art</span></a></li><li class="MTHMWUHHfGCitem2"><a href="#"><span>Area Amenities</span></a></li><li class="MTHMWUHHfGCitem2"><a href="#"><span>Shopping</span></a></li></ul></div></div><script type="text/javascript" src="cssmenutools/scripts/MTHM1.js">/* MTHMMenu script ID:MTHMWUHHfGC */</script></div>
      <!-- End Navigation -->
      <!-- Begin Page Content -->
      <div id="page_content">
      <!-- Begin Left Column -->
      <div id="column_l" style="left: 0px; top: 0px; background-color: #FFFFFF; width: 96%;">
      <!-- TemplateBeginEditable name="content" -->
      <h2 style="width: 99%; position: relative; left: -20px; top: 0px; color: #000000; font-size: xx-large; font-family: 'Arial Black';">Headline 2</h2>
      <p style="z-index: 1; width: 1712px; height: 19px; position: absolute; top: 53px; left: 10px">insert content here</p>
      <!-- TemplateEndEditable --></div>
      <!-- End Left Column -->
      <!-- Begin Right Column -->
      <div id="column_r" style="width: 22%; background-color: #FFFFFF;">
      <!-- TemplateBeginEditable name="sidebar" -->
      <h3 style="width: 375px; background-color: #FFFFFF; color: #000000;">Headline 3</h3>
      <p>insert content here</p>
      <!-- TemplateEndEditable --></div>
      <!-- End Right Column --></div>
      <!-- End Page Content -->
      <!-- Begin Footer -->
      <div id="footer">
      <p style="border-bottom-color: #DCEFFC; border-color: #BCE1FC; width: 98%; background-color: #BCE1FC; border-left-color: #BCE1FC; border-right-color: #BCE1FC; border-top-color: #BCE1FC; color: #000000;">
      <br />
      <img alt="USBCA" height="150" src="images/usbcha-logo-200.gif" style="float: left" width="118" class="auto-style3" /><br />
      <br />
      <br />
      Last Updated  May 20, 2014<br />
      Copyright &copy; 2014 Hotchkiss Sheep Camp Stock Dog Trials.  All Rights Reserved.<br />
      <br />
      <br />
      <br />
      <br />
      Powered by
      Solutions Ark</p>
      </div>
      <!-- End Footer --></div>
    <!-- End Container -->
    </form>
      </body>
      </html>

  • Converting FC Express to FCP10 (for beer)

    Hello. I have three Final Cut Express projects that need to be converted to Final Cut Pro 10.
    I need to open the project in Final Cut 7
         • Export to XML
         • Open in the app  7toX
         • Export into a new project usable in FCP10
    I only have three projects that need converting. Would anybody be willing to make these conversions for me? I  would be very pleased to buy you a couple of virtual beers through PayPal.
    Fingers crossed.  
    ( not only do I not have Final Cut Pro 7,  but I don't have the 7toX app needed.)
    Brad
    PS.   there might be another way I have not thought of to get Final Cut express files into Final Cut 10. But my searching of these forums seems to reveal that this is the best way.

    You're a total rock star!  The projects open and look correct.
    But darn...you're right.  Relinking is a pain...not working right.
    Check out the following files screenshots.  (I can't imagine I've changed the framerate somehow.... And the length of the clips is long enough. : (
    What's your paypal email?
    — Brad

  • Converting-expression-format-to-use-in-different-environment

    Hi,
    I am working on a POC project to automate migration of reports from one BI tool to another BI tool. Idea is to extract report column details along with column formula/expression and use it in another BI tool to generate report.
    For example syntax for if-else in one product is - "If Not(IsNull([col1])) Then 1 Else 0" and the equivalent expression in another product is -"if( col1 != null, 1, 0)"
    Please suggest an approach to convert an expression to different format to be used by different tool.
    Thanks
    Tilak

    exFAT would also be a supported format between the 2 operating system.
    NOTE:  FAT32 or exFAT is ONLY good for an external disk or USB Flash Drive that you are going to connect to one system, then disconnect and connect to the other.
    If you do not have a lot of data to transfer save at once (and it is not super sensitive), you might just consider getting a DropBox.com account and use the network to transfer your files.
    If the Mac and the Windows systems are on the same network, then you can also use file sharing from either system.

  • Parsing an Algebraic Expression

    Hi ,
    Can any body provide me an idea to parse an algebraic expression in Java.Are there any built in classes for parsing an expression and evaluating after substituting the values for variables in the expression?
    If no classes are availble,plz provide me any algorithm for doing that.
    Thanks in Advance

    Observe:
    Parsing an expression is essentially the act of converting the expression from infix notation to postfix notation. Infix requires parens and precedence to specify order of operations but post fix unambiguously specifies them by the order of the tokens
    So something like
    "a+b*c" becomes "a b c * +"
    "a*b+c" becomes "a b * c +"
    "(a+b)*c" becomes "a b + c *"
    notice that arguments (variables and numbers, the leaves of the implied expression tree) occur in the same sequence in both the infix and the postfix notation. Thus you can view the parsing as a filtering process that passes arguments directly from input to output and all the filter is doing is re-arranging the order of the operators.
    All this rearranging of operators can be done with a single stack and it is all based on this observation:
    When you saw a string like "a op1 b op2 c" you run across the token for the first operator before you have even collected its right argument. You must put that operator somewhere and a OpStack is the place to put it. You don't know whether to emit op1 until you have had a look at the next operator, op2. If op2 was higher priority than op1, then op2 gets to consume the argument b first. In that case op2 just gets added to the stack on top of op1.
    However if op2 was less than or equal in precedence to op1, well then op1 can now be flowed to the output stream and allowed to act on the b argument that is already out on the output stream.
    This means that the fundamental operation of the expression parser is the business of pushing an opertor token onto the stack, but first spewing to the output all the other operators on the stack that had a higher or equal priority. If we give this function a name like opStack.pushSpew(token) it could look something like this:
    class OpStack{
      Stack s = new Stack();
      void pushSpew(List out, Token t){
        Token tos;
        while(!s.empty() && (tos = peek()).priority >= t.priority){out.add(pop());}
        push(t);
    }Next thing to observe is that a grouper, like open and close parens, behaves in the following way. An open paren acts like a very high priority operator when pushed to the stack in that it spews nothing. The previous op is NOT allowed to eat the argument that is about to come right after the open paren. However once the open paren marks the stack, the open should be a lower priority than any real op that gets pushed onto the stack above it because it must delay going out until every real op in the group had its shot. The close paren should also act like a very low priority op. It should spew every op upto but not including the open paren that started this group.
    As a computation trick, if you set the priority of an open lowest of all, and the priority of a close just above that, and you just push the open onto the stack instead of pushSpewing it onto the stack, you will get the desired behavior. You with then pushSpew the close paren and it will dump everything from the stack to the output up to but not including the open. At this point it is easy to check the balance. If you do not have an open/close pair sitting as the top two elements on the stack then the parens (or the brackets or the braces) were not properly nested.
    We are almost done. There are post fix operators like factorial and prefix operators like minus that we need to deal with. It only makes sense to evaluate these suckers from the inside out i.e. if you had a string of prefixs on an arg
    op1 op2 op3 arg
    the only sensible order is defined by parens like this
    (op1 (op2 (op3 arg) ) )
    and in post fix that would be
    arg op3 op2 op1
    that is exactly what you would get if you just pushed each prefix op onto the stack in the order you saw them and then popped them off after you dumped out the argument.
    Post ops should also work from the inside out
    arg op1 op2
    being
    ( (arg op1) op2 )
    and you get this behavior by just dumping a post op to the output when you see it.
    There is only one special concern. What should you do if you saw, both pre ops and post ops on the same arg?
    is "op1 arg op2" done like this: "(op1 arg) op2" or "op1 (arg op2)"? Well, why should these be any different from regular diadic ops, let precdence decide. An espression like minus three factorial "-3!" should be interpreted as take the factorial of 3 and then negate it (and not the other way around!) so let the priority of factorial be greater than that of minus and just do the standard pushSpew with post ops to let them spew out any high priority pre ops before they go onto the stack, but then unlike binary ops, the post op immediately comes off the stack and goes to the output because post ops bind up right away.
    Now if you are not careful with your precedences you could get "wierd" behavior. If for example you did not assign a high priority to a factorial, you could write expressions like "3+4!" and the priority would treat that like "(3+4)!" the plus would bind tighter than the factorial. It is hard for me to imagine a language where you would want the effects of either a postfix or a prefix operator to span across multiple arguments combined by single diadic operator, but that is really up to you. You certainly could have a language where you gave a very low precedence to ~ which could mean the boolean NOT, a lower precedence than the diadic operator >= which would allow you to write "~ a >= b" which would mean "~(a>=b)"
    After all it is your language, do what you want. None the less I would advise against alowing ANY pre or post op to have a priority LESS than that of ANY diadic operator.
    Lots of talk here but to recap, the code is quite simple:
    while((t = getNextToken()) != null){
      switch (t.type()){
        case ARG:  out.add(t); break; // arguments pass straight to output
        case PRE:  stack.push(t); break; // pre ops are just pushed (binding them to the next arg)
        case OPEN: stack.push(t); break; // Opens just push, they don't spew to output
        case DI: stack.pushSpew(out,t); break; // Diadic ops do the standard pushSpew
        case POST: stack.pushSpew(out,t); out.add(stack.pop()); break; //spew and then go out
        case CLOSE: stack.pushSpew(out,t); stack.removeOCpair(); // spew all ops in group
          // and then check if you had a balancing open
    }That just about does the entire parse. If you can find the tokens in the input you can rearrange them into the output. You do need to flush the opStack when you are done with the input stream and there is a convenient trick to doing that. The trick is this. Invent an invisible Open and Close pair, invisible meaning that they never show up in any input stream, you just made them up and pretended that that expression started with an invisible OpenExp and at the end it closed with a CloseExp.
    The CloseExp at the end will act like any grouper, it will flush the stack looking for the corresponding opener. IF there was any unbalanced grouper, like say an extra unbalanced open paren somewhere in the expression, the CloseExp will spew its way down to that unbalanced paren and then fail when it discovers that it does not match the open in the call to remove the OC pair. The is a way to do error detection. Use a fictional group on the entire expression to both flush the remainder of the opStack and to do a final check for unbalanced groupers.
    In fact, while we are on the topic of error checking there is another one that is very good to include. Basically in a real expression if you ignore the parens, the progression should be an alternation between args and diadic ops, with an occasional pre or post op thrown in.
    A simple count tells you where you are. Go up to 1 when you pass an argument, go back down to zero when you see a diadic operator. You should start at zero, because there have been no arguments or ops yet. In state zero the only legal things to do are to put in a pre op or an arg. Once you have an arg out there the only legal things to do are to have a post op or a diadic op. This little state machine will tell you if and when you have got either a pair of arguments together with no op between them, or a pair of ops with no argument between them. You should start at state = 0 and you should end at state = 1 (unless you allow empty expressions) So we can beef up the error checking with a very simple addition. The guts of the parse will now look like this:
    state = 0
    stack.push(Token.OpenExp); // start off with an open of the expression
    while((t = getNextToken()) != null){
      switch (t.type()){
        case ARG:  assertStateIs(0); out.add(t); state = 1; break;
        case PRE:  assertStateIs(0); stack.push(t); break;
        case OPEN: stack.push(t); break;
        case DI: assertStateIs(1); stack.pushSpew(out,t); state =0; break;
        case POST: assertStateIs(1);stack.pushSpew(out,t); out.add(stack.pop()); break;
        case CLOSE: stack.pushSpew(out,t); stack.removeOCpair();
    stack.pushSpew(out,Token.CloseExp); stack.removeOCpair();
    assertState(1);
    return out;So - there it is, in outline form the way that you parse an expression.You build 3 classes, Token, ExpressionParser, and OpStack
    Token is just a bucket that holds a name, a type (ARG, PRE, OPEN, DI, ...) and a precedence.
    OpStack is just a wrapper for a reqular stack that will hold Tokens and allow for a pushSpew function.
    ExpressionParser is little other than a Map full of all your Tokens. This map allows the parser to map substrings, tokens, that it finds in the input like >= to actual Tokens with a capital T. It will have two main methods:
    1) the parse method which I have almost completly written for you. It takes an input string and will fill up an output list placing the Tokens in post fix order, which is your parse tree.
    2) the routine getNextToken which will walk the input string, skipping white space when appropriate, looking for names, numbers, and operators and building each chunk that it finds into a Token.
    One last complexity note. If you want to allow functional notation like sqrt(3) you are using parens in a fundamentally different way than was described above (ditto when you use brackets to represent array indexing like x[5]) the fundamentally different thing that you are doing is that you are allowing an argument (a name) like "sqrt" to sit right next to another argument like "3" with no binary op in between. You are using an "implied" binary op at that point. You have saved the user from typing "sqrt FUNCTIONCALL (3)" or "x ARRAYINDEX 5"
    I will leave it as an exercise to the reader to see how you make a small modification to the OPEN case to detect and deal with an implied operation. Don't forget that you must tell the state error checker what you are doing.
    And now that I have shown you how fundamentally simple it is to build an expression parser let me comment on why you do not find a standard library routine for doing this.
    The primary reason is that there is no such thing as a "standard" math expression. Parsing is based on a language and there is no one language. Are you going to allow hex numbers in your expressions? How about scientific notation? Is = equality or assignment? Do you allow functional notation? Array indexing? Multi-dimensional array (like x[2,3])? How about string constants like "foobar"? How do you embed quotes in your quoted strings? Are you allowing comments, block comments, statements, code, Lisp expressions, complex numbers, implicit type conversion, type casting? At what point does it stop being a simple expression and start being a full computer language?
    Furthermore, most of the work you will quickly see if you use what I have suggested to build an expression parser, it how to give your user feedback that the expression that he typed had problems and where. There is no stardard UI for error feedback in things that don't parse correctly. Are you just going to dump cryptic strings to the console or are you going to highlight something in a text box somewhere?
    All the work turns out to be that of defining your language and determining your set of tokens and what precedence you will employ. Once you get that all worked out, parsing the expressions only takes the ten or fifteen lines of code that I outlined.
    And look, it only took several thousands of words to explain why it only takes about 15 lines of code to parse expressions once you have decided upon your language and written your tokenizer.
    Enjoy

  • Creating a PostFix Expression!

    Hi guys I've been working in this project all day and I still can't really come up with a solution.
    What I'm doing is allowing the user to enter a infix expression such as a + b * c and an output with the postfix expression should appear in this order.
    A - Will go to a string
    + To Stack
    B To String
    * To Stack
    Then With a presedence method I should be able to determine if which operator has a higher value.
    Output Should look like:
    abc * +
    Here is my code so far I will appreciate some help or advice. Thank you
    import java.util.*;
    class Expression
         private String inFixString;
         private String postFixString;
         private String stringToken;
         public Expression()
             inFixString = "";
              postFixString = "";
         public void getInfix(String inFix)
              inFixString = inFix;               
         public void showInfix()
              System.out.println("This is the In Fix Expression : ");
              System.out.println(inFixString);
         public void showPostFix()
              System.out.println(postFixString);
         public void convertToPostFix()
              //Parsing out the string store in InFixString.
              StringTokenizer tokenizeString = new StringTokenizer(inFixString);
              Stack putInFixInStack = new Stack();
              boolean status = tokenizeString.hasMoreTokens();
              boolean stackStatus = putInFixInStack.isEmpty();
              String currentOp = "";
              while(tokenizeString.hasMoreTokens())
                   stringToken = tokenizeString.nextToken();
                   //Reading Current Token if is a letter add it to postFix Expression
                   if (Character.isLetter(stringToken.charAt(0)))
                        postFixString += stringToken;     System.out.println("Number : " + stringToken + " was appended to Post Fix");    
                  }//ABC          [     *+]
                  switch (stringToken.charAt(0))//   A + B  * C   post  AB + C -  |||||||||||||||||  GETTING ABC -+
                        case '(': System.out.println("( " + " was Push into Stack");
                             putInFixInStack.push("(");
                        break;
                        case ')':System.out.println(")" + " was Push into Stack");
                             putInFixInStack.push(")");
                        break;
                        case '+':
                             if (putInFixInStack.isEmpty())
                                  putInFixInStack.push("+");
                                  System.out.println("+" + " was Push into Stack");          
                             else
                                  putInFixInStack.push("+");
                                  System.out.println("+" + " was Push into Stack");
                                  while(stackStatus)
                                           currentOp = putInFixInStack.peek().toString();
                                       if (precedence(currentOp.charAt(0)) == 1)
                                            putInFixInStack.pop();
                                       else if (precedence(currentOp.charAt(0)) == 2)
                                            putInFixInStack.pop();
                                            postFixString += currentOp;
                                       else if (precedence(currentOp.charAt(0)) == 3)
                                            postFixString += currentOp;
                                            putInFixInStack.pop();
                                       else if (precedence(currentOp.charAt(0)) == 4)
                                            postFixString += currentOp;
                                            putInFixInStack.pop();
                                       else
                                       stackStatus = putInFixInStack.isEmpty();
                        break;
                        case '-':
                             if (putInFixInStack.isEmpty())
                                  putInFixInStack.push("-");
                                  System.out.println("-" + " was Push into Stack");
                             else
                                  putInFixInStack.push("-");
                                  System.out.println("-" + " was Push into Stack");
                                  while(stackStatus)
                                           currentOp = putInFixInStack.peek().toString();
                                       if (precedence(currentOp.charAt(0)) == 1)
                                       putInFixInStack.pop();
                                       else if (precedence(currentOp.charAt(0)) == 2)
                                            postFixString += currentOp;
                                            putInFixInStack.pop();
                                       else if (precedence(currentOp.charAt(0)) == 3)
                                            postFixString += currentOp;
                                            putInFixInStack.pop();
                                       else if (precedence(currentOp.charAt(0)) == 4)
                                            postFixString += currentOp;
                                            putInFixInStack.pop();
                                       stackStatus = putInFixInStack.isEmpty();
                        break;
                        case '*':
                             if (putInFixInStack.isEmpty())
                                  putInFixInStack.push("*");
                                  System.out.println("*" + " was Push into Stack");
                             else
                                  putInFixInStack.push("*");
                                  System.out.println("*" + " was Push into Stack");
                                  while(stackStatus)
                                           currentOp = putInFixInStack.peek().toString();
                                       if (precedence(currentOp.charAt(0)) == 1)
                                            putInFixInStack.pop();
                                       else if (precedence(currentOp.charAt(0)) == 2)
                                            postFixString += currentOp;
                                            putInFixInStack.pop();
                                       else if (precedence(currentOp.charAt(0)) == 3)
                                            postFixString += currentOp;
                                            putInFixInStack.pop();
                                       else if (precedence(currentOp.charAt(0)) == 4)
                                            postFixString += currentOp;
                                            putInFixInStack.pop();
                                       stackStatus = putInFixInStack.isEmpty();
                        break;
                        case '/':System.out.println("/" + " was Push into Stack");
                             putInFixInStack.push("/");
                        break; default:
              postFixString += putInFixInStack.peek().toString();
              stackStatus = putInFixInStack.isEmpty();
              System.out.println();
              System.out.println("Post Fix Has : " + postFixString);
         private int precedence(char in)
            switch(in)
                  case '/':
                       return 5;
                  case '*':
                     return 4;
                case '+':
                        return 3;
                case '-':
                    return 2;
                case '(': case ')':
                    return 1;
              return 0;
        public boolean isOperator()
             String[] operators = { "+" , "-" , "/" , "*" , "(" , ")" };
             boolean isOp = false;
             for( int i  = 0; i < operators.length;i++)
                  if (operators[i] == "+" )
                  isOp = true;
                  else if (operators[i] == "-" )
                  isOp = true;
                  else if (operators[i] == "/" )
                  isOp = true;
                  else if (operators[i] == "*" )
                  isOp = true;              
                  else if (operators[i] == "(")
                  isOp = true;
                  else if (operators[i] == ")" )
                  isOp = true;
                  else
                  isOp = false;
             return isOp;
         public  boolean equals(String otherElement)
              // If Current Token == Other Element return true otherwise False
              if (stringToken == otherElement)
              return true;
              else
              return false;
    }

    Here is the another java program
    which implements same algorithm & it works!!!
    Hope that it helps.
    I have run your program but it does not print anything!!!
    So I wrote my own!!!!
    //By Prafulla V Tekawade
    //[email protected]
    import java.util.*;
    class MyExpression
         public String inFix;
         public String postFix;
         public MyExpression(String str)
              inFix="("+str+")";
              postFix="";
         public void convert()
              Stack opstk=new Stack();
              int m=inFix.length();
              int i;
              for(i=0;i<m;i++)
                   if(!isOperator(inFix.charAt(i)))
                        if(inFix.charAt(i)!=')')
                             postFix += inFix.charAt(i);
                   if(inFix.charAt(i) == '(')
                        opstk.push(inFix.charAt(i));
                   if(isOperator(inFix.charAt(i)))
                        if(opstk.isEmpty())
                             while(getPriority((Character)opstk.peek()) >= getPriority(inFix.charAt(i)))
                                  postFix += opstk.pop();
                        opstk.push(inFix.charAt(i));
                   if(inFix.charAt(i) == ')')
                        char ch=(Character)opstk.pop();
                        while((ch != '(') && (!opstk.isEmpty()))
                             postFix += ch;
                             ch=(Character)opstk.pop();
              while((!opstk.isEmpty()))
                   char ch=(Character)opstk.pop();
                   if(ch!='(')
                        postFix += ch;
         public boolean isOperator(char ch)
              switch(ch)
                   case '+':
                   case '-':
                   case '/':
                   case '*':
                   case '(':
                             return true;
                   default:
                             return false;
         public int getPriority(char ch)
              switch(ch)
                   case '(':
                             return 0;
                   case '+':
                   case '-':
                             return 1;
                   case '*':
                   case '/':
                   case '%':
                             return 2;
              return -1;
         public void printPostFix()
              System.out.println (postFix);
         public static void main(String []args)
              MyExpression obj=new MyExpression("(a+b)*c");
              obj.convert();
              obj.printPostFix();
    Output
    Infix     := a+b*c
    PostFix     := abc*+
    Infix      := (a+b)*c
    PostFix := ab+c*
    Infix:=  (a+((b*c+(p*q)))+(a+(b-c)))+(d+w)+(d*q)
    PostFix= abcpq*+*abc-+dw+dq*++++
    */

  • Postfix Expressions Problem

    I wrote a program for my AP Comp Sci A class that takes a postfix expression (e.g. 32+) and converts it into an infix expression (e.g. 3+2) and then solves it. It worked before I converted it into the 'solve' method, but now I did (because its required), it keeps giving me an EmptyStackException on the line "if(comparingyay.compareTo("+")==0)
                         stk.push(stk.pop()+stk.pop());"
    If anyone can help me debug this, I would be forever greatful.
    import java.util.*;
       import java.io.*;
        public class PostfixExpressions                                                                                                                             
           public static void main(String[] args)
             Scanner scan=new Scanner(System.in);
             String in=scan.next();
             int answer=solve(in);
             System.out.println(answer);
           public static int solve(String y)
             Stack<Integer> stk= new Stack<Integer>();
             for(int x=0;x<y.length();x++)
                char chars1=y.charAt(x);
                if(Character.isLetterOrDigit(chars1))
                   Integer ints=new Integer(0);
                   stk.push(ints.valueOf(y.substring(x,x+1)));
                String comparingyay=y.substring(x,x+1);
                if(comparingyay.compareTo("+")==0||comparingyay.compareTo("-")==0||
                   comparingyay.compareTo("*")==0||comparingyay.compareTo("/")==0)
                   if(!stk.isEmpty())
                      if(comparingyay.compareTo("+")==0)
                         stk.push(stk.pop()+stk.pop());
                      else if(comparingyay.compareTo("-")==0)      
                         int b=stk.pop();
                         int a=stk.pop();
                         stk.push(a-b);
                      else if(comparingyay.compareTo("/")==0)
                         int b=stk.pop();
                         int a=stk.pop();
                         stk.push(a/b);
                      else if(comparingyay.compareTo("*")==0)
                         stk.push(stk.pop()*stk.pop());
             return stk.pop();
       }

    You don't check for the number of elements in your stack, you just check whether it's empty and, if not, pop 2 elements (though it might be only 1) off it.
    Your program looks rather C-ish; equality checking on Strings is done via equals(), compareTo() is, uhm, unconventional. Though you don't need to check Strings at all while you have chars1.
    The Integer conversion part could be done this way:
    stk.push(new Integer(chars1 - '0'));Edit: apart from these comments, your program works for me with the input "32+".

  • Hi!!!How can I change the options in a VI express?

    I want to scale a signal, and I am using the vi express "Scaling and Mapping". But!!!!I want to control the differents "options" that I can choose, linear scale, slope...How can I do it? I don´t know if it is possible in a vi Express. I know that I can change the properties of controls and indicators using properties nodes, but I thing that it doesn´t work in this case, but I am not sure!!!!
    Thank you!!!
    Graci

    First thing to do is to convert the express VI to a standard subVI by right clicking on it and selecting Open Front Panel. Then, select which front panel controls that you want and add them to the connector pane.

  • How can I view the color ramp in LV 8.6 sensor-mapping express vi during run-time?

    Hi All, 
    I've been using the sensor mapping express VI that is new in LV 8.6. When I place the express vi in my block diagram of my main vi I get the normal 'express' style configuration dialog. As a part of the configuration there is a really nice 'color-ramp' control where I can configure ranges; max; min; out -of-range colors and so on.
    What I would like to do is have the color-ramp control appear as a control on my main vi's front panel. After I convert the express VI to a regular VI I can't seem to find the connection to this control. Although I have found the sub-vi that the expressvi uses in an .llb here:
    C:\Program Files\National Instruments\LabVIEW 8.6\vi.lib\express\express 3d picture\SensorConfig.llb
    Can anyone point me in the right direction to do this? I get so deep into all the sub-vi's I end up getting lost-haha!
    Thanks - Paul

    The characteristics of the color ramp (max, min, colors) are all part of a "colorrampstuff" cluster that is inside the Sensor Mapping express VI. In order to change those values for the express VI, you will need to create a custom express VI that provides you with inputs to this cluster. This is done similarly to creating a subVI. Then you can use a variety of methods to write to the elements in this cluster and change them while the program is running.
    It may be easier to place numeric controls on the front panel that write directly to the elements in the cluster than to use a color ramp as a control.
    Will
    Certified LabVIEW Architect, Certified Professional Instructor
    Choose Movement Consulting
    choose-mc.com

  • Expression pedal not working in Logic after upgrading to Lion

    I'm having a problem where Logic 9 isn't recognizing the expression pedal (CC#11) MIDI messages coming from my M-Audio Axiom 61 keyboard after I upgraded to Lion.  I've reset the settings on the Axiom, made sure the pedal was set properly and plugged in to the correct port.  (Also, it's an m-audio expression pedal) The display on the Axiom says it's receiving the midi controller messages.  Logic is receiving the mod wheel and pitch bend messages, and sustain pedal messages.  On the midi activity monitor in the transport bar and in the environment clicks and ports window, it's the same.  Everything but the CC#11 messages are coming through.  Also the expression pedal DOES still work in Mainstage.
    I've also tried creating a new Logic project, but it still doesn't work.
    Any ideas?

    Also, for the sake of experimenting, I assigned the Axiom to convert the expression pedal messages to CC#2.  When I did that, Logic DID receive it (as CC#2).  So then in the Environment clicks and ports layer, I made a transformer object to turn it back into CC#11.  So that's my work around for now.
    Also, I tried, on the Axiom, assigning my Mod wheel to CC#11 (so that it's sending CC#11 to Logic when I move the mod wheel.)  And then Logic also DIDN'T receive it at all.
    So it seems that Logic doesn't like paying attention to CC#11 messages right now.

  • How to close a write to file express VI

    Hi, 
    I am using an Write to File express VI inside a subVI in LabVIEW 7.1.  Since it is in a DAQ loop it is configured to create only one file even though it is called many times. 
    The problem I am having is that when the subVI itself is closed and reopened the express VI does not prompt to create a new file.  Is there a way to get around this? 
    I am hoping there is some sort of invoke or property node that I can use on either the express VI or the subVI itself to close or "reset" it.
    Does a subVI stay in memory even after the front panel is closed?  I am guessing this is what is causing my problem.  Any ideas?
    I do realize the BEST thing to do here would be to simply not use an express VI but I am hoping there is a way to fix this without going that far yet.  From what I can tell LV7.1 does not allow me to convert an express VI to code which makes it look like it will take even longer to rewrite this.
    For now the solution we have in place is the following:  close the subVI, close the main program (the calling VI), and then reload.  
    Thanks,
    Dave

    dave,
    if i remeber correcty... there is a file path option will be available with the express vi... I actualy can not reproduce this here since i dont have LV 7.1. So if you feel that the express vi does not gives you a prompt for selecting the file path, then just place a "File dialog" function before the express vi and wire the selected path.
    Regards
    Guru (CLA)

  • Query Transformation in Function Based Index's Expression

    Hi All,
    I am having a wired issue with Function Based Indexes on Orcale 10.2.0.3 running on Solaris 5.9.
    I have created two FBI on two tables using following syntax.
    CREATE INDEX EQHUB.IDX_BBO_WRT_DES_FBI ON EQHUB.BBO_WARRANT_PRICING (CASE WHEN latest_version_flag = 'Y' THEN 1 ELSE NULL END);
    CREATE INDEX EQHUB.IDX_BBO_DES_FBI ON EQHUB.BBO_DESCRIPTIVE_DATA (CASE WHEN latest_version_flag = 'Y' THEN 1 ELSE NULL END);
    For the second command (IDX_BBO_DES_FBI), when i query DBA_IND_EXPRESSIONS view, i found that Oracle has done some kind of QUERY TRANSFORMATION (?) and converted
    FBI expression to CASE "LATEST_VERSION_FLAG" WHEN 'Y' THEN 1 ELSE NULL END.At the same time,EXPRESSION on first index is not changed.
    Now,my question is what has made transformation to occure only for second index.
    I also found that inspite of highly SELECTIVE nature of both the indexes, only SECOND index is being used by CBO (for which trasnformation occured)
    and IDX_BBO_WRT_DES_FBI is not being used(FTS is happening instead).
    Query is using same expression for both the tables as
    (CASE WHEN latest_version_flag = 'Y' THEN 1 ELSE NULL END)=1
    INDEX_NAME                          TABLE_NAME                          COLUMN_EXPRESSION
    IDX_BBO_WRT_DES_FBI                 BBO_WARRANT_PRICING                 CASE  WHEN "LATEST_VERSION_FLAG"='Y' THEN 1 ELSE NULL END
    IDX_BBO_DES_FBI                     BBO_DESCRIPTIVE_DATA                CASE "LATEST_VERSION_FLAG" WHEN 'Y' THEN 1 ELSE NULL ENDI read that expression should be evaluated including CASE of characters and spaces in query.Is that true?
    Appreciating responses in advance.

    Randolf.
    It's a shame that I forgot to look into the full execution plan information to check how Oracle really handles my queries.
    Look here(edited for clarity):
    explain plan for
    select /*+ case1 ordered use_nl(x, y) */ count(case c1
        when '1' then 1
        when '2' then 2
        when '3' then 3
        else 4
      end) from
    (select level from dual connect by level <= 300000) x,
    (select
    from t1
    ) y;
    | Id  | Operation                       | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT                |      |     1 |     2 |     5   (0)| 00:00:01 |
    |   1 |  SORT AGGREGATE                 |      |     1 |     2 |            |          |
    |   2 |   NESTED LOOPS                  |      |     3 |     6 |     5   (0)| 00:00:01 |
    |   3 |    VIEW                         |      |     1 |       |     2   (0)| 00:00:01 |
    |   4 |     CONNECT BY WITHOUT FILTERING|      |       |       |            |          |
    |   5 |      FAST DUAL                  |      |     1 |       |     2   (0)| 00:00:01 |
    |   6 |    TABLE ACCESS FULL            | T1   |     3 |     6 |     3   (0)| 00:00:01 |
    Column Projection Information (identified by operation id):
       1 - (#keys=0) COUNT(CASE  WHEN "T1"."C1"='1' THEN 1 WHEN "T1"."C1"='2' THEN
           2 WHEN "T1"."C1"='3' THEN 3 ELSE 4 END )[22]
       2 - (#keys=0) "T1"."C1"[CHARACTER,1]
       4 - "DUAL".ROWID[ROWID,10], LEVEL[4]
       5 - "DUAL".ROWID[ROWID,10]
       6 - "T1"."C1"[CHARACTER,1]
    32 rows selected.
    explain plan for select /*+ case2 ordered use_nl(x, y) */ count(case
        when c1 = '1' then 1
        when c1 = '2' then 2
        when c1 = '3' then 3
        else 4
      end) from
    (select level from dual connect by level <= 300000) x,
    (select
    from t1
    ) y;
    | Id  | Operation                       | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT                |      |     1 |     2 |     5   (0)| 00:00:01 |
    |   1 |  SORT AGGREGATE                 |      |     1 |     2 |            |          |
    |   2 |   NESTED LOOPS                  |      |     3 |     6 |     5   (0)| 00:00:01 |
    |   3 |    VIEW                         |      |     1 |       |     2   (0)| 00:00:01 |
    |   4 |     CONNECT BY WITHOUT FILTERING|      |       |       |            |          |
    |   5 |      FAST DUAL                  |      |     1 |       |     2   (0)| 00:00:01 |
    |   6 |    TABLE ACCESS FULL            | T1   |     3 |     6 |     3   (0)| 00:00:01 |
    Column Projection Information (identified by operation id):
       1 - (#keys=0) COUNT(CASE  WHEN "T1"."C1"='1' THEN 1 WHEN "T1"."C1"='2' THEN
           2 WHEN "T1"."C1"='3' THEN 3 ELSE 4 END )[22]
       2 - (#keys=0) "T1"."C1"[CHARACTER,1]
       4 - "DUAL".ROWID[ROWID,10], LEVEL[4]
       5 - "DUAL".ROWID[ROWID,10]
       6 - "T1"."C1"[CHARACTER,1]As you exactly mentioned, I was executing different SQL but actually same queries!
    Thanks for pointing my flaws.
    PS) OP, forgive me for bothering you with off-topic things. :)
    ================================
    Dion Cho - Oracle Performance Storyteller
    http://dioncho.wordpress.com (english)
    http://ukja.tistory.com (korean)
    ================================
    Edited by: Dion_Cho on Feb 10, 2009 5:45 AM
    Typo

  • ColdFusion Builder 3 Express - Debug support

    Hi,
    I have coldfusion 10 and wanted to know if I get ColdFusion Builder 3 trial version. After 60 days, it will get converted to express edition, I wanted to know if debugging will work with express edition.
    Thanks in advance.
    Regards,
    Dharmendra

    I believe it is a feature that is disabled entirely in the express edition.  I can't confirm that though, as I have a full license to ColdFusion Builder.
    -Carl V.

  • Can express vi handle large data

    Hello,
    I'm facing problem in handling large data using express vi's. The input to express vi is a large data of 2M samples waveform & i am using 4 such express vi's each with 2M samples connected in parallel. To process these data the express vi's are taking too much of time compared to other general vi's or subvi's. Can anybody give the reason why its taking too much time in processing. As per my understanding since displaying large data in labview is not efficient & since the express vi's have an internal display in the form of configure dialog box. Hence i feel most of the processing time is taken to plot the data on the graph of configure dailog box. If this is correct then Is there any solution to overcome this.
    waiting for reply
    Thanks in advance

    Hi sayaf,
    I don't understand your reasoning for not using the "Open Front Panel"
    option to convert the Express VI to a standard VI. When converting the
    Express VI to a VI, you can save it with a new name and still use the
    Express VI in the same VI.
    By the way, have you heard about the NI LabVIEW Express VI Development Toolkit? That is the choice if you want to be able to create your own Express VIs.
    NB: Not all Express VIs can be edited with the toolkit - you should mainly use the toolkit to develop your own Express VIs.
    Have fun!
    - Philip Courtois, Thinkbot Solutions

Maybe you are looking for

  • CSS 3.0 Problem

    Facing some problem plz help me out:- How to create rounded box with help of CSS 3.0

  • Reading in text file

    I have a text file that contains something like this: <setting name="ip_address" serializeAs="String">                 <value>239.0.0.1</value> I want to be able to search through the text file and based upon finding <setting name="ip_address" serial

  • How do I connect my MFC-J630w brother printer to my ipad?

    My brother printer is not an AirPrint is there any other way to connect it to my ipad2 ?

  • DB Read error from UCCX Script

    Hi All, We are running uccx 7.0. Trying to return data from DB using stored procedure from the uccx script. We are able to run this when we pass explicit value instead of variable ANI. But whenever we provide variable ANI, we get below error: SQL sta

  • Include a dialog screen in tabstrip of selection-screen

    Hi All, Could anyone please tell me how to include a dialog screen into selection-screen? We have a normal selection screen for a report but now we need to add some more function and this requires to key in material number in first column and quantit