-2

I'm a fairly beginner coder and I'm working on a project of mine, although I'm having trouble, I've looked online for anything that can help but I can't seem to be able to do it. I'm trying to create a program that solves algebriac equations, I've managed to split the whole string into two lists, I can then join the lists together but it only prints as a string, I can't print it as a float or an integer.

import re
group1 = []
group2 = []
subjects = []
question = input("What is the question?")
questions = list(question)

for i in range(len(questions)):
    if questions[i] == "=":
        for a in range(i):
            group1.append(questions[a])
        print(group1)
        a = a + 2
        for b in range(a,len(questions)):
            group2.append(questions[b])
        print(group2)

for i in range(len(group1)):
    if re.match("[a-z]", str(group1[i])):
        subjects.append(group1[i])
print(subjects)

for i in range(len(group2)):
    if re.match("[a-z]", str(group2[i])):
        subjects.append(group2[i])

pair1 = ''.join(group1)
pair2 = ''.join(group2)
print(int(pair1))
print(pair2)

(This of course isn't finished)

When it tries to print (int(pair1)), I get this error:

ValueError: invalid literal for int() with base 10: '5+6'

I need help to overcome this.

code_dredd
  • 5,915
  • 1
  • 25
  • 53
  • 1
    What result do you want to get from printing expressions as int or float? – dizballanze Jan 19 '16 at 22:58
  • Your whole first loop does `group1, group2 = question.split("=", 1)` – TessellatingHeckler Jan 19 '16 at 23:00
  • What input causes the error? – Paul Rooney Jan 19 '16 at 23:04
  • Hi Max, welcome to SO. Remember to keep an eye on your question so that you can clarify doubts for those trying to help. Remember to come back to consider up-voting and accepting the answer you consider most useful. It benefits you, those trying to help, and the community at large. You also take a look at [How do I Ask a Good Question?](http://stackoverflow.com/help/how-to-ask). – code_dredd Jan 19 '16 at 23:29

2 Answers2

1

When it tries to print (int(pair1)), I get this error : ValueError: invalid literal for int() with base 10: '5+6'.

The string '5+6' is not a valid number. This is easily reproduced. For example:

>>> int('5+6')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5+6'

You need to break the string apart into its separate numbers (i.e. 5 and 6) and then add them together. Consider this instead:

>>> intlist = [int(i) for i in '5+6'.split('+')]
>>> sum(intlist)
11
>>> # just displaying list
>>> intlist
[5, 6]

The code above uses a list comprehension, and is basically equivalent to the code below:

>>> strlist = '5+6'.split('+')
>>> intlist = []
>>> for i in strlist:
...     intlist.append(int(i))
...
>>> sum(intlist)
11
>>> # just displaying lists for you
>>> strlist
['5', '6']
>>> intlist
[5, 6]

The list comprehension I used above does this in roughly 2 lines of code; the one below is more compact, elegant, and Pythonic:

>>> sum(int(i) for i in '5+6'.split('+'))
11

Security: Why you shouldn't abuse eval and exec

The eval and exec functions are powerful, but this power brings dangers with it in the sense that it's easier to screw things up. (Everything is a trade-off.)

So, while writing eval('2+2') might seem tempting, you should consider the security implications of it, and err on the side of safety and avoid its use if you're not sure or don't have a more knowledgeable person/team that can review the code (if this is meant for production).

The main problem is that eval will not only execute arbitrary mathematical expressions, but will in fact attempt to execute anything you send to it before it is validated and deemed to be safe.

For example, suppose you ask the user to enter an expression to evaluate, and from the user's PoV, it looks like this:

Enter a mathematical expression: 2+5+7+1
15

It works! But rule #1 of software development is: You never trust user input

If you put your code in your server/page and it looks like this:

>>> eval(input('Enter a mathematical expression: '))

Guess what will happen when I as a user enter the following input?

>>> Enter a mathematical expression: print([int(i) for i in '2+5+7+1'.split('+')])

Indeed, the result would be:

>>> [2, 5, 7, 1]

And your "simple" and "innocent" app is now being used to execute arbitrary code in your system.

I'm not saying you should "never" use these. What I am saying is that you need to know what you're doing before you do.

Consider these other SO posts:

code_dredd
  • 5,915
  • 1
  • 25
  • 53
  • And what happens when there are multiple operators (not exclusively addition)? – Jared Goguen Jan 19 '16 at 23:08
  • @o_o: This is a simple example to illustrate the problem and one way to go about it. Obviously, if his problem is more complicated, Max will need to device a better solution for it. It's likely that some kind of parser will be needed for more complicated expressions, especially if other symbols (e.g. parentheses for order of operations) will be present. – code_dredd Jan 19 '16 at 23:15
-1

Try splitting your pairs first, calling int() on each individual number instead of on the whole expression. So, for example, if pair1 is the string "5+4", do something like this:

first_num_str,second_num_str = pair1.split("+") 
first_num = int(first_num_str)
second_num = int(second_num_str)
result = first_num + second_num
print(str(result))

Of course, you'll have to change the split() expression for "-","*", or other arithmetic operators, and use float() if your numbers are not integers.