Solved

how to access command line in a program

Posted on 2004-10-28
416 Views
Last Modified: 2010-04-16


Hello guys,

My problem is simple, when I develop a program in command line I can perfrom anything what I want.

I have a class file and have a overloaded operator +.If I am in command line I can perform anything what I want but if i am in the program while it is executed  I have no choice except rawinput.I want my program let me write anything like in command line shell .

Thanks
0
Question by:hermesc
    25 Comments
     
    LVL 11

    Expert Comment

    by:cjjclifford
    you might want to have a look a the "readline" library (unix availablity), this provides standard unix shell-like input (history, completion, etc).
    0
     

    Author Comment

    by:hermesc
    NO I just need a command ( like rawinput) which lets me to pass variables expressions directly to program

    for instance during my program instead rawinput my program will get this
    a+b
    and it will turn the value as if it is in shell
    0
     
    LVL 11

    Accepted Solution

    by:
    ok, I think I have you now...

    eval( rawinput() )
    0
     
    LVL 11

    Expert Comment

    by:cjjclifford
    for example:

    print eval( raw_input( 'enter math equation: ' ) )
    enter math equation: 10 + 20 * 100
    2010
    0
     
    LVL 17

    Expert Comment

    by:ramrom
    Also consider the input() function, which equates to eval( rawinput() )

    Bob Gailer, Page Editor
    0
     

    Author Comment

    by:hermesc
    okey guys,
    lets clear everything.I have got a class called polynomial.
    For instance p=polynomial({1:1,2:2}) creates a polynomial X+X^2
    now this can be entered in shell when you import the polynomial class.
    Problem is my lecturer wants me to generate a "p" during the program.How can I do it? raw_input sucks.How can I get that polynomial while I am in program ( my class is ready and I am getting crazy !!! )
    0
     

    Author Comment

    by:hermesc
    The original problem is on this site
    http://courses.eng.ku.edu.tr/cmse501/assignment2.pdf
    I have done the class.But dont know how to assign a polynomial ( p=polynomial(.....)) by using raw_input etc.....
    0
     

    Author Comment

    by:hermesc
    lets increase it.....
    0
     

    Author Comment

    by:hermesc
    hello guys,

    I have found something
    below code has imported poly class and in raw_input if you say
    p=poly(.....)

    and execute it and print p it will work however
    The user is not limited to p! So what can I do then?


    while 1:
    i=raw_input("Type something: ")
    if i=="quit":
    break
    exec i
    print "The value of p is:",p
    0
     

    Author Comment

    by:hermesc
    Ok guys, I handle it

    while 1:
          i=raw_input("type some")
          if i=="quit":
                break
          exec i
    if you type something executable such as polynomial.mult(a,b) and this polynomial member prints something then you display your expression !
    0
     
    LVL 17

    Expert Comment

    by:ramrom
    Thanks for the link http://courses.eng.ku.edu.tr/cmse501/assignment2.pdf. it gives some context.

    I am often amazed at the extent of assignments in an "introductory class". This assignment is not trivial, especially for the 2nd assigment.

    In order to meet the requirements for:

    Enter a polynomial:
    p = 7x^2 + 5

    the program must
    1 - get the variable name (p)
    2 - get  the first term (7x^2) and split it into the c value (7) and the e value (2)
    3 - execute p = Polynomial(e,c)
    4 - get the next term (5) and split it into the c value (5) and the e value (0)
    5 - execute p = p.add(Polynomial(e,c))

    Am I on the right track for what you need?

    Bob Gailer, Page Editor
    0
     
    LVL 1

    Expert Comment

    by:mces
    'k, time to pay.  Grab it from here: http://www.cs.toronto.edu/~behdad/poly.py
    It does everything you want, and much more.  For example you can ask for p(p(x)').
    0
     

    Author Comment

    by:hermesc
    Well guys,
    thanks for your helps but I have done the code except I execute only p+q and not p+q+z' ( do not have idea how to find a solution for this).

    Bob : yes ,

    So far I have done except entering the polynomial like p=7x^14.... like that ( I still have to enter p=polynomial(....)
    0
     
    LVL 1

    Assisted Solution

    by:mces
    Seems like you don't like URLs.  I put an hour and wrote it from scratch.  You can pick the bits you like.  Here goes the complete code for the whole assignment:

    #!/usr/bin/python

    class Polynomial:

          class Derivative:
                pass

          def __init__(p, e = None, c = None):
                if c == 0 or e == None:
                      p.__dict = {}
                elif e.__class__ == dict:
                      p.__dict = e.copy()
                elif e.__class__ == Polynomial:
                      p.__dict = e.__dict.copy()
                else:
                      p.__dict = {e: 1}
                if c <> None:
                      for key in p.__dict:
                            p[key] = p[key] * c
          
          def mult(p, q):
                r = Polynomial()
                if q.__class__ == Polynomial:
                      for a in p.__dict:
                            for b in q.__dict:
                                  r[a+b] = r[a+b] + p[a] * q[b]
                else:
                      for key in p.__dict:
                            r[key] = p[key] * q
                return r

          def __mul__(p, q):
                return p.mult(q)

          def __rmul__(p, q):
                return p.mult(q)

          def __div__(p, q):
                # Only scalar division
                return p.mult(1/q)

          def __pow__(p, q):
                if q.__class__ == Polynomial.Derivative:
                      return p.derivative()
                elif q == 0:
                      r = Polynomial(0, 1)
                elif q == 1:
                      r = p.copy()
                elif q % 2 == 1:
                      r = p**int(q / 2)
                      r = r * r * p
                elif q % 2 == 0:
                      r = p**(q/2)
                      r = r * r
                return r

          def add(p, q):
                if q.__class__ == Polynomial:
                      r = p.copy()
                      for i in q.__dict:
                            r[i] += q[i]
                else:
                      r = p.add(Polynomial(0, q))
                return r

          def __add__(p, q):
                return p.add(q)

          def __radd__(p, q):
                return p.add(q)

          def __sub__(p, q):
                return p.add(-q)

          def __rsub__(p, q):
                return (-p).add(q)

          def negate(p):
                r = p.copy()
                for i in r.__dict:
                      r[i] = -r[i]
                return r

          def __neg__(p):
                return p.negate()

          def derivative(p):
                r = Polynomial()
                for i in p.__dict:
                      if i:
                            r[i-1] = p[i] * i
                return r
          
          def __invert__(p):
                return p.derivative()

          def getCoef(p, e):
                if p[e] == 0:
                      return (0, 0)
                else:
                      return (e, p[e])

          def __getitem__(p, i):
                return p.__dict.get(i, 0)

          def __setitem__(p, i, v):
                if v == 0:
                      if i in p.__dict:
                            del p.__dict[i]
                else:
                      p.__dict[i] = v
          
          def __str__(p):
                k = p.__dict.keys()
                k.sort()
                k.reverse()
                if len(k):
                      s = ""
                      for i in k:
                            v = p[i]
                            if v < 0:
                                  s += " - "
                            else:
                                  s += " + "
                            v = abs(v)
                            if v <> 1 or i == 0:
                                  s += str(v)
                            if i <> 0:
                                  s += "x"
                                  if i <> 1:
                                        s += "^"+str(i)
                      if s[1] == "-":
                            s = s[1]+s[3:]
                      else:
                            s = s[3:]
                      s = "(" + s + ")"
                else:
                      s = "0"
                return s
          
          def __call__(p, x):
                r = 0
                for i in p.__dict:
                      r += p[i] * x**i
                return r

          def copy(p):
                r = Polynomial()
                  r.__dict = p.__dict.copy()
                return r

    x = Polynomial(1)

    if __name__ == "__main__":
          import re
          while True:
                try:
                      line = raw_input("Enter a polynomial: ")
                except EOFError:
                      print
                      break
                if line == "END":
                      break
                line = line.replace("^", "**")
                line = line.replace("'", "**Polynomial.Derivative()")
                (line, junk) = re.subn("([0-9])(x)", r"\1*\2", line)
                if not re.match(".*=", line):
                       line = "print " + line

                try:
                      exec line
                except Exception, e:
                      print e
    0
     
    LVL 11

    Expert Comment

    by:cjjclifford
    mces, since this is homework, you should not provide complete solutions, only assist the author in areas of difficulty.

    hermesc, I would take care if you decide to use mces' solution as your solution - there are several things that will loose you points from a homework perspective (complete lack of comments (sorry, there is one comment...), for one thing, other things also, including variable named something other than "self" for the object's self-reference in the class method definitions...) Also, since your assignment states that you may be chozen to present your assignment to the class, you would really want to know exactly how it works, etc...
     
    0
     
    LVL 11

    Expert Comment

    by:cjjclifford
    hermesc, if there is a piece of code you are having problems with, post the code, and hopefully we can help you find the solution...
    0
     
    LVL 1

    Expert Comment

    by:mces
    Hehe, I find the problem interesting enough to code the whole thing, but I didn't try to be too neat for exactly same reason.

    BTW, the self thing, I found it really neat to use p instead of self in this special program.  Thanks for you comments.
    0
     

    Author Comment

    by:hermesc
    Ok guys, I am almost in the end of the code

    class polynomial:
          # type in increasing form of keys(orders)
          # p =polynomial({0:1,1:2,2:3,3:6})
          def __init__(self,x):
                self.exp=x.keys()
                self.coef=x.values()
          def add(self,other):
                tempe=[]
                tempc=[]
                tempc[:]=self.coef[:]
                tempe[:]=self.exp[:]
                for j in range(len(other.coef)):
                      
                      c=0
                      for i in range(len(self.coef)):
                            
                            if tempe[i]==other.exp[j]:
                                  tempc[i]+=other.coef[j]
                                  c+=1
                            else :
                                  c+=0
                      if c==0:
                            tempc+=[other.coef[j]]
                            tempe+=[other.exp[j]]
                for j in range(len(tempe)-1):
                      for i in range(len(tempe)-1):
                              if tempe[i]>tempe[j]:
                                 tempe[i],tempe[j]=tempe[j],tempe[i]                
                                         tempc[i],tempc[j]=tempc[j],tempc[i]
                    for i in range(len(tempc)-1):
                      print "%dx^%d+"%(tempc[i],tempe[i]),
                i =len(tempc)
                print "%dx^%d"%(tempc[i-1],tempe[i-1])

                result={}

                for i in range(len(tempe)):
                      temp={tempe[i]:tempc[i]}
                      result.update(temp)
                res=polynomial(result)      

                return (res)
                   
                   
                  def __add__(self,other):
                """overloading addition"""

                return(self.add(other))


         

    This is a part of my code , when I type a+a+a+a ( polynomial it prints all the operations ( no problem with this and prints a the adress of a,  )

    >>> a=polynomial({1:1,2:2,3:3})
    >>> a+a+a+a
    2x^1+ 4x^2+ 6x^3
    3x^1+ 6x^2+ 9x^3
    4x^1+ 8x^2+ 12x^3
    <pazartesi.polynomial instance at 0x00A6D490>






    0
     
    LVL 11

    Expert Comment

    by:cjjclifford
    hi Hermesc,

    just a few comments,

    1. Your post seems to have lost some formatting, which generally isn't a problem, but in Python it is, since Python uses indentation for block limitation....

    2. in the add() method:

              tempe=[]
              tempc=[]
              tempc[:]=self.coef[:]
              tempe[:]=self.exp[:]

    can be replaced with:
            tempe = self.coef[:]
            tempc = self.exp[:]

    3. You definitely want to add some comments to the large loops in the add() method - this is a bit "magic", and is well worth explaining...

    4. After the loops:

     i =len(tempc)
              print "%dx^%d"%(tempc[i-1],tempe[i-1])

    can be replaced with:
              print '%dx%d' % ( tempc[-1], tempe[len(tempc)] )

    or even
            print '%dx%d' % ( tempc[-1], tempe[-1] )
    if len(tempc) == len( tempe )

    It may be worth saying that the assignment described using lists of tupples to represent the polynomial, you are using 2 lists...
    To convert a map (the {1:1...} construct) to a list to tupples use the following:

    # sample mapping...
    map = { 1:2, 2:3, 4:1 }
    tupple_list = zip( map.keys(), map.values() )

    Then accessing this:
    COEF=1
    EXP=0

    coef_0 = tupple_list[ 0 ][COEF]

    hope this helps...
    C.
    0
     

    Author Comment

    by:hermesc
    guys thank you a lot! you earn more then  ( I have only 210 available ) 350. Thanks again a lot!
    0
     

    Author Comment

    by:hermesc
    Meanwhile I will appreciate if you can provide me several computational exercises ( this is a introductional course but a 501 course, a masters :=) I am expected to develop graphical programs add the end of the course )
    Thanks again
    0
     
    LVL 17

    Expert Comment

    by:ramrom
    All please note the EE Member Agreement http://www.experts-exchange.com/memberAgreement.jsp especially the last bullet under guidelines:
    - Violating the guidelines for academic honesty or other unethical behavior,
      it is allowable to help a student with a project, but not doing it for them.

    Bob Gailer, Page Editor
    0
     
    LVL 17

    Expert Comment

    by:ramrom
    This is further clarified in the EE Help page http://www.experts-exchange.com/help.jsp#hi130

    "Most commonly, this means that Experts are prohibited from doing your homework for you. They'll guide you and teach you, but don't ask them to write code to answer a question that seems like it was written for a test. It should be noted that just like bribery, while it's bad to offer a bribe, it's worse to take it -- so don't do homework.

    "Homework" is loosely defined as an assigment, project or quiz offered up an instructor of a technical, trade or eductional institution as part of a scheduled course of instruction, for which the student receives some kind of credit. The Moderators know what homework looks like, and it will be your task to convince them it isn't."
    0
     
    LVL 1

    Expert Comment

    by:mces
    Sorry.  Will not happen again.
    Maybe I should have had written my ideas instead of implementing them.
    Some notable ideas are:
      - Instead of parsing the string, MODIFY it and pass it to eval.
      - Since there is no postfix unary operator in python, I decided to use x**Some.Class() to represent x' (derivative).  Then in the __pow__, I can identify that all I'm asked to do is to call derivative.  This is the only easy way I can think of to make the derivative operator work.
      - Another idea is to define x as a Polynomial(0, 1).  It works automagically good with your overloaded operators.
      - __call__ can be overloaded for evaluating the polynomial, just using power, multiplication and addition, which means, you can then compute neat things like p(q(x)) with no additional burdon.

    Thanks it,
    Sorry again for breaking the rules.
    Behdad Esfahbod
    0
     
    LVL 17

    Expert Comment

    by:ramrom
    Thanks for appreciating and respecting the homework policy. And welcome to the team of Experts!

    Bob Gailer, Page Editor
    0

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone. Privacy Policy Terms of Use

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    Suggested Solutions

    Plenty of writing has gone on the web trying to compare Python with other competitive programming languages and vice versa. However, not much has been put into a wholistic perspective. This article should help you decide whether to adopt Python as a…
    "The time has come," the Walrus said, "To talk of many things: Of sets--and lists--and dictionaries-- Of variable kinks-- And why you see it changing not-- And why so strange are strings." This part describes how variables and references (see …
    Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
    Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

    875 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    7 Experts available now in Live!

    Get 1:1 Help Now