Equation Solving with python - python

There is a question like that:
1 X2 X 3 X 4 X 5 X 6 X 7 X 8 X 9 = 1942
X = must be x,+,-,รท operators or nothing(89, 123 could be etc.)
How can i solve this problem with python?
Thanks.

You can start with something like this:
from itertools import product
target = 1942
test_str = "1{0[0]}2{0[1]}3{0[2]}4{0[3]}5{0[4]}6{0[5]}7{0[6]}8{0[7]}9"
for a in product(["*", "", "+", "/", "-", ""], repeat=8): # Iterate all posibilites
result_str = test_str.format(a)
if eval(result_str) == target:
print(result_str)
break
And optimize and make it more expandable to more numbers. But for your specific problem this works fine. I found this solution:
1*2/3+4*56*78/9
Take a look at eval if you need more information.

You can use parser module from python
import parser
formula = "1 + 2 + 3 + 4 + 5 * 6 * 7 * 8 * 9"
code = parser.expr(formula).compile()
print eval(code)

Related

For looping and storing variables for math operations in python

Total newbie question here. I have been looking around here and other internet searches and cannot find a great solution. I am scripting some geometry variables in the software Ansys. It is called spaceclaim and they use IronPython for the scripting language. I cannot at this time import numpy to take advantage of any libraries.
I am trying to pattern a set of points, where the points are a function of a geometric parameter. I tried to boil it down for clarity:
(the numbering and equations are meaningless, just wanted to lay out an example that illustrates my problem)
i=0
S_1 = 3
S_= []
xpi_ = []
ff_= 2
np=4
for i in range(np):
S_[i + 2] = S_[i + 1] + 10 * ff_
xpi_[i + 2] = (S_[i + 1])**2
So in this example:
first loop
S_2 = S_1 + 10 * ff = 23
xpi_2 = S_1**2 = 9
second loop
S_3 = S_2 + 10 * ff = 43
xpi_3 = S_2**2 = 529
...
When I execute it jupyter I get this:
----> 8. S_[i + 2] = S_[i + 1] + 10 * ff_
IndexError: list index out of range
Much appreciated for any help!
John
use this code:
S_=[S_1]
for i in range(np):
S_.append(S_[i] + 10 * ff_)
xpi_.append((S_[i])**2)

recursive function multiply and sum

Hope to find some help here with a new excercise.
I luckily understand how to use recursive functions, but this one is killing me, im probably just thinking too much outside of the box.
We're given a string:
c = "3+4*5+6+1*3"
And now we have to code a function, which recursivly gives us the result of that calculation.
Now i know the recursive end should be the length of the string, which should be 1.
Our professor did give us another example which we should use for this function.
int(number)
string.split(symbol, 1)
we have following code given:
c = "3+4*5+6+1*3"
print(c)
print()
sub1, sub2 = c.split("+", 1)
print("Result with '+':")
print("sub1=" + sub1)
print("sub2=" + sub2)
print()
sub1, sub2 = c.split("*", 1)
print("Result with '*':")
print("sub1=" + sub1)
print("sub2=" + sub2)
print()
My thoughts were to split the strings to a minimum, so i can turn them into integers and than sum them together. But im absolutly lost there how the code should look like, im a real beginner so im really sorry. I dont even know it the beginning i was thinking of is right. Still hoping, someone can help!
what i had:
def calc(string):
if len(string) == 1:
return string
Thanks for all of you!
Greets
Chrissi
I created a function that solves equations like these. However, the only characters possible are numbers, and operators add (+) and mult (*). If you try to use any other characters such as spaces, there's going to be errors.
# Solves a mathematical equation containing digits [0-9], and operators
# such as add + or multiply *
def solve(equation, operators, oindex=0):
# If an operator is available, use the operator
if (oindex < len(operators)):
# Get the current operator and pair: a op b
op = operators[oindex]
pair = equation.split(op, 1)
# If the pair is a pair (has 2 elements)
if (len(pair) == 2):
# Solve left side
a = solve(pair[0], operators)
# Solve right side
b = solve(pair[1], operators)
# If current operator is multiply: multiply a and b
if (op == '*'):
print(a, '*', b, '=', a*b)
return a * b
# If current operator is add: add a and b
elif (op == '+'):
print(a, '+', b, '=', a+b)
return a + b
# If it's not a pair, try using another operator
else:
return solve(equation, operators, oindex+1)
else:
# If no operators are available, then equation is
# just a number.
return int(equation)
if __name__ == '__main__':
equation = "3+4*5+6+1*3"
# If mult (*) takes precedence, operator order is "+*"
# > 3+4*5+6+1*3 = ((3)+((4*5)+((6)+(1*3))))
# = ((3)+((20)+((6)+(3))))
# = ((3)+(20+(9)))
# = ((3)+(29))
# = (32)
print("MULT, then ADD -> ",equation + " = ", solve(equation, "+*"))
# If add (+) takes precedence, operator order is "*+"
# > 3+4*5+6+1*3 = ((3+4)*(((5)+(6+1))*(3)))
# = ((7)*((5+7)*(3)))
# = ((7)*(12*3))
# = (7*36)
# = (252)
print("ADD, then MULT -> ",equation + " = ", solve(equation, "*+"))
To set the operators, you can use the paramter operators, which is a string that takes all supported operators. In this case: +*.
The order of these characters matter, changing the precedence of each operator inside the equation.
Here's the output:
4 * 5 = 20
1 * 3 = 3
6 + 3 = 9
20 + 9 = 29
3 + 29 = 32
MULT, then ADD -> 3+4*5+6+1*3 = 32
3 + 4 = 7
6 + 1 = 7
5 + 7 = 12
12 * 3 = 36
7 * 36 = 252
ADD, then MULT -> 3+4*5+6+1*3 = 252

seven (7) boom game in one line code python

I need to create a game that every number that divides in 7 or has the digit 7 should be printed as boom:
[1 2 3 4 5 6 boom 8 ... 13 boom 15 16 boom ...]
my line get invalid text. I think its because of the mix of int and str. not shore what to do to fix the code.
boom7 = [x = "boom" if 7 in x else x*1 for x in range(1,99)]
print(boom7)
almost, this should do it
[ "boom" if "7" in str(x) or x%7==0 else x for x in range(1,99)]
let me know if you need explaining
def seven_boom(end_number):
for x in range(0,end_number+1):
str_first = str(x)
replace_first_num = str_first.replace(str_first[0],"boom")
if "7" in str_first or x%7 ==0:
new_seven_boom = str_first.replace(str_first,"boom")
print(new_seven_boom)
else:
print(x)
replace_last_num = str_first.replace(str_first[-1],"boom")
seven_boom(27)

Need information on Basic Python Arthematic operation

I am using Python Version 3.6.4
I was trying to write a basic python code in Jupyter Notebook where I found my code acting funny.
The below given code is working as expected But when I change the operation to (+) in the 4th line of code print( x, '+', y, '=', x+y) then it is resulting with Error.
Question is why is this unexpected behavior happening when there is a change of operator where multiplication works fine and addition results with error?
def fuc(x):
x = input('Enter the number:')
for y in range(1,11):
print( x, 'x', y, '=', x*y)
print(fuc(2))
The user input (i.e. x) is string. y is integer. Multiplication between string and integer is valid python operation. Addition between integer and string is not. Note that I doubt your code with multiplication works as expected, i.e. it will not multiply the number, but repeat the string, e.g.
>>> '3' * 4
'3333'
To deal with the problem you need to convert the user input to int:
x = int(input('Enter the number:'))
Note that this will not handle any invalid input, e.g. not numeric input and will raise an exception.
EDIT: Include example code snippet:
def fuc(x):
x = int(input('Enter the number:'))
for y in range(1,11):
print(x, '+', y, '=', x+y)
# print(f'{x} + {y} = {x+y}') # in 3.6+ you better use this
fuc(2)
output in python3
Enter the number:3
3 + 1 = 4
3 + 2 = 5
3 + 3 = 6
3 + 4 = 7
3 + 5 = 8
3 + 6 = 9
3 + 7 = 10
3 + 8 = 11
3 + 9 = 12
3 + 10 = 13
>>>
Normally I would use string formatting for the print, but in this case I keep as in the original code
you can try this piece of code:
def fuc(x):
x = float(input('please enter your desired number'))
for i in range(1,11):#generally i is used as an iterable
print( "{}*{} '=' ",x*i)
print(fuc())

While Loop to produce Mathematical Sequences?

I've been asked to do the following:
Using a while loop, you will write a program which will produce the following mathematical sequence:
1 * 9 + 2 = 11(you will compute this number)
12 * 9 + 3 = 111
123 * 9 + 4 = 1111
Then your program should run as far as the results contain only "1"s. You can build your numbers as string, then convert to ints before calculation. Then you can convert the result back to a string to see if it contains all "1"s.
Sample Output:
1 * 9 + 2 = 11
12 * 9 + 3 = 111
123 * 9 + 4 = 1111
1234 * 9 + 5 = 11111
Here is my code:
def main():
Current = 1
Next = 2
Addition = 2
output = funcCalculation(Current, Addition)
while (verifyAllOnes(output) == True):
print(output)
#string concat to get new current number
Current = int(str(Current) + str(Next))
Addition += 1
Next += 1
output = funcCalculation(Current, Next)
def funcCalculation(a,b):
return (a * 9 + b)
def verifyAllOnes(val):
Num_str = str(val)
for ch in Num_str:
if(str(ch)!= "1"):
return False
return True
main()
The bug is that the formula isn't printing next to the series of ones on each line. What am I doing wrong?
Pseudo-code:
a = 1
b = 2
result = a * 9 + b
while string representation of result contains only 1s:
a = concat a with the old value of b, as a number
b = b + 1
result = a * 9 + b
This can be literally converted into Python code.
Testing all ones
Well, for starters, here is one easy way to check that the value is all ones:
def only_ones(n):
n_str = str(n)
return set(n_str) == set(['1'])
You could do something more "mathy", but I'm not sure that it would be any faster. It would much more easily
generalize to other bases (than 10) if that's something you were interested in though
def only_ones(n):
return (n % 10 == 1) and (n == 1 or only_ones2(n / 10))
Uncertainty about how to generate the specific recurrence relation...
As for actually solving the problem though, it's actually not clear what the sequence should be.
What comes next?
123456
1234567
12345678
123456789
?
Is it 1234567890? Or 12345678910? Or 1234567900?
Without answering this, it's not possible to solve the problem in any general way (unless in fact the 111..s
terminate before you get to this issue).
I'm going to go with the most mathematically appealing assumption, which is that the value in question is the
sum of all the 11111... values before it (note that 12 = 11 + 1, 123 = 111 + 11 + 1, 1234 = 1111 + 111 + 11 + 1, etc...).
A solution
In this case, you could do something along these lines:
def sequence_gen():
a = 1
b = 1
i = 2
while only_ones(b):
yield b
b = a*9 + i
a += b
i += 1
Notice that I've put this in a generator in order to make it easier to only grab as many results from this
sequence as you actually want. It's entirely possible that this is an infinite sequence, so actually running
the while code by itself might take a while ;-)
s = sequence_gen()
s.next() #=> 1
s.next() #=> 11
A generator gives you a lot of flexibility for things like this. For instance, you could grab the first 10 values of the sequence using the itertools.islice
function:
import itertools as it
s = sequence_gen()
xs = [x for x in it.islice(s, 10)]
print xs

Categories