How do you split a string after a symbol in python? - python

import sympy
equation = input('Enter an equation: ')
a = equation.split(('=') or ('<') or ('>') or ('<=') or ('>=') or ('==') or ('!='))[0:2]
b = sympify(a[0])
c = sympify(a[1])
d = simplify(b - c)
print('This is the equation simplified: ' + str(d))
I want to split the equation in two parts when one of the symbols (=,<,>,>=,<=,==,!=) appear, but in this code it only works when the '=' sign is the symbol.

I think your code should be like that:
import re #<--- add this
import sympy
equation = input('Enter an equation: ')
a = re.split(r'[=|<|>|<=|>=|==]', equation)[0:2] #<--- only change this
b = sympify(a[0])
c = sympify(a[1])
d = simplify(b - c)
print('This is the equation simplified: ' + str(d))

Related

How to get variable values from a txt file with a specified format?

I am writing a program that solves quadratic equations, with the variables assigned from a .txt file, with this specific format:
The text file will contain lines of comma separated text – each line contains three floating point numbers. The first number is the value for A, the second number is the value for B, and the third number is the value for C.
Now I have my code mostly written out I am just unsure how I would assign these variables from a .txt file. Here is my current code:
print("\nWelcome to the Blockhouse Bay College Quadratic Equation Program")
file = input("\nPlease input text file name: ")
file = file + ".txt"
text_file = open(file, "r")
import math
# function for finding roots
def equationroots( a, b, c):
# calculating discriminant using formula
dis = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(dis))
# checking condition for discriminant
if dis > 0:
print("There are two distinct roots ")
print((-b + sqrt_val)/(2 * a))
print((-b - sqrt_val)/(2 * a))
elif dis == 0:
print("There is one real root")
print(-b / (2 * a))
# when discriminant is less than 0
else:
print("Complex Roots")
print(- b / (2 * a), " + i", sqrt_val)
print(- b / (2 * a), " - i", sqrt_val)
# Driver Program
#<---------------Need these variables assigned to lines from .txt file
a = 1
b = 10
c = -24
# If a is 0, then incorrect equation
if a == 0:
print("Cannot be a quadratic equation if a is zero")
else:
equationroots(a, b, c)
Note: Please note at the start of my code I have asked the user to input the file name, I still need to work on this as I need to create an error message for when the file does not exist. Just ignore this as I can fix that later.
with open('file.txt') as f:
content = f.read()
for line in content.splitlines():
a, b, c = map(float, content.split(','))
Complete program:
print("\nWelcome to the Blockhouse Bay College Quadratic Equation Program")
import math
# function for finding roots
def equationroots( a, b, c):
# calculating discriminant using formula
dis = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(dis))
# checking condition for discriminant
if dis > 0:
print("There are two distinct roots ")
print((-b + sqrt_val)/(2 * a))
print((-b - sqrt_val)/(2 * a))
elif dis == 0:
print("There is one real root")
print(-b / (2 * a))
# when discriminant is less than 0
else:
print("Complex Roots")
print(- b / (2 * a), " + i", sqrt_val)
print(- b / (2 * a), " - i", sqrt_val)
filename = input("\nPlease input text file name: ")
with open(filename + '.txt') as f:
content = f.read()
for line in content.splitlines():
a, b, c = map(float, content.split(','))
# If a is 0, then incorrect equation
if a == 0:
print("Cannot be a quadratic equation if a is zero")
else:
equationroots(a, b, c)
Try this:
I had to move some of your code around, but I left inline comments to explain what I changed. I also included a check to make sure the path exists.
import math # Python convention is to put imports at the top
import os
print("\nWelcome to the Blockhouse Bay College Quadratic Equation Program")
# function for finding roots
def equationroots( a, b, c):
# calculating discriminant using formula
dis = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(dis))
# checking condition for discriminant
if dis > 0:
print("There are two distinct roots ")
print((-b + sqrt_val)/(2 * a))
print((-b - sqrt_val)/(2 * a))
elif dis == 0:
print("There is one real root")
print(-b / (2 * a))
# when discriminant is less than 0
else:
print("Complex Roots")
print(- b / (2 * a), " + i", sqrt_val)
print(- b / (2 * a), " - i", sqrt_val)
file = input("\nPlease input text file name: ")
file = file + ".txt"
if os.path.exists(file): # check if file exists
with open(file, "rt") as text_file: # using a with statement is
# preferred over directly
# opening the file
for line in text_file: # iterate through lines of file
# the next line splits the `line` by "," commas,
# removes whitespace and casts each item to float
a,b,c = [float(i.strip()) for i in line.split(',')]
if a == 0:
print("Cannot be a quadratic equation if a is zero")
else:
equationroots(a, b, c)
else:
# print some message
you could read the file like this:
f = open(file_name,"r")
for line in f.readlines():
a,b,c = map(float,line.split(","))
# now call your function
if a == 0:
print("Cannot be a quadratic equation if a is zero")
else:
equationroots(a, b, c)
we started by opening the file then we iterate over the lines using file.readlines() then for every line we splitted the values and converted all of them to a float using map()

Calculate the value of a function for given coordinates

I am new here. I want to write a neat litte program to check the solutions of my exam preparations as my professor didnt provide any. For a non- linear differential equation f I want to find the 1st Taylor polynomial. Therefore I take the derivative of f in respect to every variable.
Now my problem:
I have to calculate the value of each derivative for a certain given point. How can I do that for such complex expressions that are just stored in a variable and not explicitly known, as they are calculated?
This is what i do now, without evaluating:
f = input('Enter function: ')
fy1 = diff(f,y1)
fy = diff(f,y)
fu2 = diff(f,u2)
fu1 = diff(f,u1)
fu = diff(f,u)
I tried this function as I hoped it would recognize the variables in f automatically:
def calculate(f,y1,y,u2,u1,u):
return f
...
fy1 = calculate(diff(f,y1),0,-1,0,0,-4)
fy = calculate(diff(f,y),0,-1,0,0,-4)
fu2 = calculate(diff(f,u2),0,-1,0,0,-4)
fu1 = calculate(diff(f,u1),0,-1,0,0,-4)
fu = calculate(diff(f,u),0,-1,0,0,-4)
Edit:
I tried out something else:
For f= -5yy1+4*y-u (y1 is the derivative of y)
fy1 is the derivative of f in respect to y1:
fy1= diff(f, y1)
fy1.subs([(y1,0),(y,-1),(u2,0),(u1,0),(u,-4)])
print("{}".format(fy1))
But subs() didnt substitute any values as the output was the following:
-5*y
I guess it has something to so with the variables being defined as sympy symbols?
y1 = symbols('y1')
y = symbols('y')
u2 = symbols('u2')
u1 = symbols('u1')
u = symbols('u')
But I need that for the sympy diff()-function
My solution for now is almost what I wrote in my first edit. What I didnt realize was that the substitution is not permanent and I had to store the solution in an extra variable.
Here is the complete program. I am open for suggestions to improve it an all aspects.
from sympy import diff, symbols
again = True
while(again):
y1 = symbols('y1')
y = symbols('y')
u2 = symbols('u2')
u1 = symbols('u1')
u = symbols('u')
f = input('Enter function: ')
fy1= diff(f, y1)
res_fy1 = fy1.subs([(y1,0),(y,-1),(u2,0),(u1,0),(u,-4)])
print("{}".format(res_fy1))
fy= diff(f, y)
res_fy = fy.subs([(y1,0),(y,-1),(u2,0),(u1,0),(u,-4)])
fu2= diff(f, u2)
res_fu2 = fu2.subs([(y1,0),(y,-1),(u2,0),(u1,0),(u,-4)])
fu1= diff(f, u1)
res_fu1 = fu1.subs([(y1,0),(y,-1),(u2,0),(u1,0),(u,-4)])
fu= diff(f, u)
res_fu = fu.subs([(y1,0),(y,-1),(u2,0),(u1,0),(u,-4)])
print('delta_y2 + (' + str(res_fy1) + ')*delta_y1 + (' + str(res_fy) + ')*delta_y + (' + str(res_fu2) + ')*delta_u2 + (' + str(res_fu1) + ')*delta_u1 + (' + str(res_fu) + ')*delta_u')
wrongInput = True
while (wrongInput):
i = input('Another function? [y/n] ')
if (i == 'n'):
again = False
wrongInput = False
elif (i == 'y'):
wrongInput = False
else:
print('Wrong Input!')

printing equation with variables in python

I am trying to print the equation with the variables
I have already tried to put all symbols in quotes
import random
import random
def ask():
a = raw_input("do you want the equation to be easy, medium, or hard: ")
b = int(raw_input("what is the number that you want to be the answer: "))
if(a == "easy"):
d = random.randint(1, 10)
e = random.randint(2, 5)
round(b)
print C = b - d + e - (e/2) + ((d - e) + e/2)
I wanted it to print out the equation with all the variables and symbols
when i type this in i get a syntax error
You cannot print out strings not in quotes. Put the bits you want to print out exactly as written in quotes, and print variables as is. For example:
print 'C =', b, '-', d, '+', e, '-', (e/2), '+', ((d - e/2)
Play around with that and see how you go. You'll want to think about how to do it differently if e.g. d-e/2 is negative.
Also round(b) will do nothing, it does not operate in-place.
try to put your equation in str() first,then print string
so that it will display equation before result.
then print out results
Here's what I think you want as a full solution. It accepts a single equation string as an input It then fills out that equation with the input variables, prints the resulting equation, and then evaluates it to provide a result:
import random
equation = "b - c + e - (e/2) + ((d- e) + e/2)"
b = 12
c = 24
d = random.randint(1, 10)
e = random.randint(2, 5)
# Expand the vlaues into the equation
equation = equation.replace('b', str(b)).replace('c', str(c)).replace('d', str(d)).replace('e', str(e))
# Print the equation
print "C = " + equation
# Evaluate the equation and print the result
C = eval(equation)
print "C = " + str(C)
Sample result:
C = 12 - 24 + 2 - (2/2) + ((6- 2) + 2/2)
C = -6
This code is just a demonstration of what can be done. You could take these ideas and generalize this to expand a map of variable names and values into an arbitrary expression without hard-coding the variable names. The map and equation could come, for example, from a file.

Python find similar sequences in string

I want a code to return sum of all similar sequences in two string. I wrote the following code but it only returns one of them
from difflib import SequenceMatcher
a='Apple Banana'
b='Banana Apple'
def similar(a,b):
c = SequenceMatcher(None,a.lower(),b.lower()).get_matching_blocks()
return sum( [c[i].size if c[i].size>1 else 0 for i in range(0,len(c)) ] )
print similar(a,b)
and the output will be
6
I expect it to be: 11
get_matching_blocks() returns the longest contiguous matching subsequence. Here the longest matching subsequence is 'banana' in both the strings, with length 6. Hence it is returning 6.
Try this instead:
def similar(a,b):
c = 'something' # Initialize this to anything to make the while loop condition pass for the first time
sum = 0
while(len(c) != 1):
c = SequenceMatcher(lambda x: x == ' ',a.lower(),b.lower()).get_matching_blocks()
sizes = [i.size for i in c]
i = sizes.index(max(sizes))
sum += max(sizes)
a = a[0:c[i].a] + a[c[i].a + c[i].size:]
b = b[0:c[i].b] + b[c[i].b + c[i].size:]
return sum
This "subtracts" the matching part of the strings, and matches them again, until len(c) is 1, which would happen when there are no more matches left.
However, this script doesn't ignore spaces. In order to do that, I used the suggestion from this other SO answer: just preprocess the strings before you pass them to the function like so:
a = 'Apple Banana'.replace(' ', '')
b = 'Banana Apple'.replace(' ', '')
You can include this part inside the function too.
When we edit your code to this it will tell us where 6 is coming from:
from difflib import SequenceMatcher
a='Apple Banana'
b='Banana Apple'
def similar(a,b):
c = SequenceMatcher(None,a.lower(),b.lower()).get_matching_blocks()
for block in c:
print "a[%d] and b[%d] match for %d elements" % block
print similar(a,b)
a[6] and b[0] match for 6 elements
a[12] and b[12] match for 0 elements
I made a small change to your code and it is working like a charm, thanks #Antimony
def similar(a,b):
a=a.replace(' ', '')
b=b.replace(' ', '')
c = 'something' # Initialize this to anything to make the while loop condition pass for the first time
sum = 0
i = 2
while(len(c) != 1):
c = SequenceMatcher(lambda x: x == ' ',a.lower(),b.lower()).get_matching_blocks()
sizes = [i.size for i in c]
i = sizes.index(max(sizes))
sum += max(sizes)
a = a[0:c[i].a] + a[c[i].a + c[i].size:]
b = b[0:c[i].b] + b[c[i].b + c[i].size:]
return sum

What's wrong with my Extended Euclidean Algorithm (python)?

My algorithm to find the HCF of two numbers, with displayed justification in the form r = a*aqr + b*bqr, is only partially working, even though I'm pretty sure that I have entered all the correct formulae - basically, it can and will find the HCF, but I am also trying to provide a demonstration of Bezout's Lemma, so I need to display the aforementioned displayed justification. The program:
# twonumbers.py
inp = 0
a = 0
b = 0
mul = 0
s = 1
r = 1
q = 0
res = 0
aqc = 1
bqc = 0
aqd = 0
bqd = 1
aqr = 0
bqr = 0
res = 0
temp = 0
fin_hcf = 0
fin_lcd = 0
seq = []
inp = input('Please enter the first number, "a":\n')
a = inp
inp = input('Please enter the second number, "b":\n')
b = inp
mul = a * b # Will come in handy later!
if a < b:
print 'As you have entered the first number as smaller than the second, the program will swap a and b before proceeding.'
temp = a
a = b
b = temp
else:
print 'As the inputted value a is larger than or equal to b, the program has not swapped the values a and b.'
print 'Thank you. The program will now compute the HCF and simultaneously demonstrate Bezout\'s Lemma.'
print `a`+' = ('+`aqc`+' x '+`a`+') + ('+`bqc`+' x '+`b`+').'
print `b`+' = ('+`aqd`+' x '+`a`+') + ('+`bqd`+' x '+`b`+').'
seq.append(a)
seq.append(b)
c = a
d = b
while r != 0:
if s != 1:
c = seq[s-1]
d = seq[s]
res = divmod(c,d)
q = res[0]
r = res[1]
aqr = aqc - (q * aqd)#These two lines are the main part of the justification
bqr = bqc - (q * aqd)#-/
print `r`+' = ('+`aqr`+' x '+`a`+') + ('+`bqr`+' x '+`b`+').'
aqd = aqr
bqd = bqr
aqc = aqd
bqc = bqd
s = s + 1
seq.append(r)
fin_hcf = seq[-2] # Finally, the HCF.
fin_lcd = mul / fin_hcf
print 'Using Euclid\'s Algorithm, we have now found the HCF of '+`a`+' and '+`b`+': it is '+`fin_hcf`+'.'
print 'We can now also find the LCD (LCM) of '+`a`+' and '+`b`+' using the following method:'
print `a`+' x '+`b`+' = '+`mul`+';'
print `mul`+' / '+`fin_hcf`+' (the HCF) = '+`fin_lcd`+'.'
print 'So, to conclude, the HCF of '+`a`+' and '+`b`+' is '+`fin_hcf`+' and the LCD (LCM) of '+`a`+' and '+`b`+' is '+`fin_lcd`+'.'
I would greatly appreciate it if you could help me to find out what is going wrong with this.
Hmm, your program is rather verbose and hence hard to read. For example, you don't need to initialise lots of those variables in the first few lines. And there is no need to assign to the inp variable and then copy that into a and then b. And you don't use the seq list or the s variable at all.
Anyway that's not the problem. There are two bugs. I think that if you had compared the printed intermediate answers to a hand-worked example you should have found the problems.
The first problem is that you have a typo in the second line here:
aqr = aqc - (q * aqd)#These two lines are the main part of the justification
bqr = bqc - (q * aqd)#-/
in the second line, aqd should be bqd
The second problem is that in this bit of code
aqd = aqr
bqd = bqr
aqc = aqd
bqc = bqd
you make aqd be aqr and then aqc be aqd. So aqc and aqd end up the same. Whereas you actually want the assignments in the other order:
aqc = aqd
bqc = bqd
aqd = aqr
bqd = bqr
Then the code works. But I would prefer to see it written more like this which is I think a lot clearer. I have left out the prints but I'm sure you can add them back:
a = input('Please enter the first number, "a":\n')
b = input('Please enter the second number, "b":\n')
if a < b:
a,b = b,a
r1,r2 = a,b
s1,s2 = 1,0
t1,t2 = 0,1
while r2 > 0:
q,r = divmod(r1,r2)
r1,r2 = r2,r
s1,s2 = s2,s1 - q * s2
t1,t2 = t2,t1 - q * t2
print r1,s1,t1
Finally, it might be worth looking at a recursive version which expresses the structure of the solution even more clearly, I think.
Hope this helps.
Here is a simple version of Bezout's identity; given a and b, it returns x, y, and g = gcd(a, b):
function bezout(a, b)
if b == 0
return 1, 0, a
else
q, r := divide(a, b)
x, y, g := bezout(b, r)
return y, x - q * y, g
The divide function returns both the quotient and remainder.
The python program that does what you want (please note that extended Euclid algorithm gives only one pair of Bezout coefficients) might be:
import sys
def egcd(a, b):
if a == 0:
return (b, 0, 1)
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def main():
if len(sys.argv) != 3:
's program caluclates LCF, LCM and Bezout identity of two integers
usage %s a b''' % (sys.argv[0], sys.argv[0])
sys.exit(1)
a = int(sys.argv[1])
b = int(sys.argv[2])
g, x, y = egcd(a, b)
print 'HCF =', g
print 'LCM =', a*b/g
print 'Bezout identity: %i * (%i) + %i * (%i) = %i' % (a, x, b, y, g)
main()

Categories

Resources