4

Python: So I am working on a program (which is a class assignment) that will take an expression such as 3/4/5 or 32432/23423/2354325 or 3425*343/254235 or 43252+34254-2435, etc(for all operators from +,-,/,*). and will solve the expression.

I CANT USE EVAL!!

I cant use higher level codes, I am limited to, at most, using string manipulators from the below website to split the string.

http://docs.python.org/2/library/stdtypes.html#typesseq

My method is to look at the expression the user enters and then use a find function to find the OPERATORS, and then use these operators and a slicing function (eg. s[0:x]). What I have is below and unfortunately it isnt working: *note that the print statements are in there for debugging purposes only. EDIT: why is x not defined when I run the program and enter an expression?

z= (input("expression:")).strip()

def finding(z):
    if "/" in z:
        x=z.find("/")
        print("hi1")
    elif "*" in z:
        x=z.find("*")
        print("hi2")
    elif "+" in z:
        x=z.find("+")
        print("hi3")
    elif "-" in z:
        x=z.find("-")
        print("hi4")
    else:
        print("error, not math expression")
    return x

def Parsing(z,x):

    x= finding(z)
    qw=z.s[0:x]
    print (qw)
# take the x-value from function finding(z) and use it to split 

finding(z)
Parsing(z,x)
SeesSound
  • 503
  • 4
  • 13
  • 24
  • 1
    Didn't you ask [a similar question](http://stackoverflow.com/questions/13055884/parsing-math-expression-in-python-and-solving-to-find-an-answer)? I know that I answered this exact question yesterday. Someone else did as well two days ago. Nobody is going to do your homework for you. – Blender Oct 30 '12 at 05:09
  • @Blender This is a completely different method that I am trying thats why it is in a new questions. You could always look at my profile and questions there to see what i've already asked before giving me a -1. I made a new question because the answers I was getting were getting far off track. I am asking something very very specific and giving the answer to it will not complete my homework therefore I didn't re-ask the same question so someone would do my homework.... – SeesSound Oct 30 '12 at 05:14
  • Can you explain what's wrong with [this answer](http://stackoverflow.com/a/13056137/464744)? – Blender Oct 30 '12 at 05:17
  • @Blender For the reasons above please reverse the negative rep. you gave me. – SeesSound Oct 30 '12 at 05:20
  • @Blender I stated in the post why I couldn't use the code. No one is looking at that post anymore and no one is giving any more feedback... – SeesSound Oct 30 '12 at 05:21
  • Have you tried to change that code to suit your needs? – Blender Oct 30 '12 at 05:22
  • @blender Yes I have, but I was unable to manipulate it and had to move on since I am not that advanced and didn't understand the code in that post completly. It is ludicrous to argue an old thread in a new one...I edited my post. If you consider that question to be cheating on my homework then alas it is impossible for me to learn computer science.. – SeesSound Oct 30 '12 at 05:28
  • Didn't you just [ask this yesterday](http://stackoverflow.com/questions/13116167/python-creating-a-calculator/13116467#13116467)? – Burhan Khalid Oct 30 '12 at 05:32
  • @BurhanKhalid No, of course not, not at all, negative. Please look at specifically what I am asking in this post. btw you never replied to my post in your answer... – SeesSound Oct 30 '12 at 05:37

3 Answers3

3

If you're just having trouble splitting the input into its parts, here's something to help you. I left it as readable as I could so that you could at least understand what it does. I'll explain any part of it if you need me to:

def parse(text):
    chunks = ['']

    for character in text:
        if character.isdigit():
            if chunks[-1].isdigit():   # If the last chunk is already a number
                chunks[-1] += character  # Add onto that number
            else:
                chunks.append(character) # Start a new number chunk
        elif character in '+-/*':
            chunks.append(character)  # This doesn't account for `1 ++ 2`.

    return chunks[1:]

Example usage:

>>> parse('123 + 123')
['123', '+', '123']
>>> parse('123 + 123 / 123 + 123')
['123', '+', '123', '/', '123', '+', '123']

I'll leave the rest up to you. If you aren't allowed to use .isdigit(), you'll have to replace it with lower-level Python code.

Blender
  • 289,723
  • 53
  • 439
  • 496
  • Nice, better than my attempt over [here](http://stackoverflow.com/questions/13116167/python-creating-a-calculator/13116467#13116467) – Burhan Khalid Oct 30 '12 at 05:47
  • @BurhanKhalid It is a placeholder in the definition of the function I believe. – SeesSound Oct 30 '12 at 05:51
  • @blender yes I can use all the code. I understand that "text" is most likely an input outside of the definition of the function. I dont understand where the variable character fits in. it is not defined in the parameters of the function but it is being used in arguments. – SeesSound Oct 30 '12 at 06:00
  • `character` is defined within the `for` loop and by the `for` loop. Take a look here: http://docs.python.org/2/tutorial/controlflow.html – Blender Oct 30 '12 at 06:04
  • Oh, I am so used to seeing "i" in place of character that I didn't realize...Anyways,The definition from the python documentation website creates ambiguity... I am assuming that character.isdigit() is an argument that states that: if "character" in "text" is a number, then move on to the indented line of argument.... is this a correct understanding of isdigit? – SeesSound Oct 30 '12 at 06:17
  • @user1716168: It could be just me, but this code isn't too far off from the plain English explanation of what you would do. `isdigit()` returns `True` if the string is composed only of digits `'1'.isdigit() == True`. – Blender Oct 30 '12 at 06:20
  • Would you mind joining me in chat? – SeesSound Oct 30 '12 at 06:23
  • @user1716168: You accidentally edited out the link – Blender Oct 30 '12 at 06:25
  • I never put a link... I have never used chat on this website but a prompt came up above asking me to move conversations to chat. Would you mind linking to one that I can join you in. – SeesSound Oct 30 '12 at 06:26
  • Oh wait, apparently I need 20 rep which I don't have yet.. Do you use anything else that youre willing to share? IRC, PM's, external messengers? – SeesSound Oct 30 '12 at 06:28
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/18771/discussion-between-blender-and-user1716168) – Blender Oct 30 '12 at 06:29
  • @user1716168: I bumped your rep up slightly. See the link above. – Blender Oct 30 '12 at 06:33
  • But I have looked at it enough and it just clicked in my mind. Please check my understanding, I am going to start at the for loop. For "character" in "text", if the "character" is a digit and if the last chunk(last character?) was a digit, then add the next "character" in "text" to "chunk"? Repeat this until the character under consideration is no longer a digit. If it is no longer a digit then move to the elif statement, create a chunk there, and then move back to the original if statement. Since chunk[-1] is no longer a dgit move to else statement and repeat.Is this correct? I have a few Q'S – SeesSound Oct 30 '12 at 06:36
2

The easiest way for doing this, I think, is implementing a Shunting-yard algorithm to convert your equation in postfix notation and then executing it from left to right.

But since this is a class assignment, you should do the actual implementation yourself, I already gave you more than I should have.

willtrnr
  • 431
  • 5
  • 15
  • Sorry this didn't help at all. A user gave me a specific example in relation to your above method and I realized I am unable to use the method. – SeesSound Oct 30 '12 at 05:23
  • So why didn't you ask a question on that method and what you are having problems with instead of repeating your entire question again? – Burhan Khalid Oct 30 '12 at 05:33
  • Actually it does fit your needs, it respects the priority of operations and it doesn't need any external libs, I know because I implemented this in Python in my spare time before. – willtrnr Oct 30 '12 at 05:36
  • @BurhanKhalid Why does no one understand that I did ask several time son my other post and people just stopped repyling... What am I to do then? The problem was never solved. I am sure it is not the nature of this site to leave a question unanswered.. Of course at least one person here will argue I am trying to cheat which is false. – SeesSound Oct 30 '12 at 05:42
  • @wiill my OP did not say I could use any built in function. It said I could use any STRING built in function... thus it does not suit my needs. damn Im getting so much heat... – SeesSound Oct 30 '12 at 05:43
  • I did it with arrays, strings and string built-in functions. Unless you're not allowed to use arrays, I don't see any problems. Also, don't take it wrong, I'm just trying to show you that my solution isn't that hard and I think it is worth trying. I could actually paste my code tomorrow if you really want. Don't expect anything beautiful though, I did it quick'n'dity. – willtrnr Oct 30 '12 at 06:04
  • I cannot use arrays/lists. Please don't post the code, I want to figure this out myself as much as possible. – SeesSound Oct 30 '12 at 06:06
  • Well it could be done using only strings, only it would be a little bit easier with lists. Also, I totally agree with not posting the code and letting you figure it out. – willtrnr Oct 30 '12 at 06:13
0

Why is x not defined when I run the program and enter an expression?

x is not in scope, you only define it in your methods, and you try to access it elsewhere.

z= (input("expression:")).strip()

def finding(z):
    # ... removed your code ...
    # in this method, you define x, which is local
    # to the method, nothing outside this method has
    # access to x
    return x

def Parsing(z,x):

    x= finding(z) # this is a different x that is assigned the 
                  # return value from the 'finding' method.
    qw=z.s[0:x] # I'm curious as to what is going on here.
    print (qw)
# take the x-value from function finding(z) and use it to split 

finding(z) # here, z is the value from the top of your code
Parsing(z,x) # here, x is not defined, which is where you get your error.

Since Parsing is already calling finding to get the value of x, you don't need to pass it into Parsing, you also don't need to call finding(z) outside Parsing, since you don't store the value anywhere.

def Parsing(z):

    x= finding(z) # this is a different x that is assigned the 
                  # return value from the 'finding' method.
    qw=z.s[0:x] # I'm curious as to what is going on here.
    print (qw)
# take the x-value from function finding(z) and use it to split 

# finding(z)  -- not needed 
Parsing(z)
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • How would I get the X that is in the first function into the second function? – SeesSound Oct 30 '12 at 07:34
  • Since you are calling the first function in the second function, and storing the result `x = finding(z)` you already have it in the second function. – Burhan Khalid Oct 30 '12 at 07:43