I am trying to parse the coefficient of "a" in a quadratic equation (ax^2 + bx + c).
However, the length of the coefficient can vary.
For instance, here are some of the intended outcomes:
input: 5x^2 + 3x + 4
output: 5
input: 12x^2 + 2x - 6
output: 12
The number could also be in the middle of the equation.
input: 2x - 3x^2 + 4
output: 3
How would I get the whole text before "x^2" until their is a white space?
I have tried using the split() function:
a = equation.split("x^2")
a = a[0]
but this would not work in the third example
Here you are
[-+]?\d+(\.\d+)?(?=x\^)
Test it here
Be aware that this regex will only match simple cases, for example, it will not match 2E3.
Tip: use RegEx 101 to test your pattern:
pattern = re.compile(r'([\+\-\d.]*)x\^2')
tests = [
'5x^2 + 3x + 4',
'12x^2 + 2x - 6',
'2x - 3x^2 + 4',
'x^2 - 2x + 1',
'-x^2 + 6x - 9'
]
for t in tests:
m = pattern.search(t)
text = m.group(1)
if text == '':
coeff = 1
elif text == '-':
coeff = -1
else:
coeff = float(text)
print(coeff)
Prints:
5.0
12.0
3.0
1
-1
I saw that using split is an option too from the question. So you want to get the whole text before the numbers with the ^ operator.
This will only work for these three examples:
x = '5x^2 + 3x + 4'
y = '12x^2 + 2x - 6'
z = '2x - 3x^2 + 4'
print(x.split()[0])
print(y.split()[0])
print(z.split('+')[0])
# split default argument is space
Output
5x^2
12x^2
2x - 3x^2
And If you want to take only the numbers with the ^ operator without the whole text before, change z.split('+')[0] to:
print(z.split()[2])
# 3x^2
Related
How can I take an argument from this list so that I can put it in place of a phone?
a10 = ' ' * (2 + length)+ (' ' * length - len(str(phone))).join([str(x) for x in range(1, boardX + 1)])
The idea is that (' ' * length - len(str(phone))) determine the space between numbers depending on whether the number is one digit, two digit, etc.
In the phone place I would like to take an argument from a list to specify the number of its characters. –
example:
boardX = 14
length = 3
output:
target output:
Use a formatting operator rather than calculating spaces yourself. Yo can specify the field width indirectly using *.
a10 = " " * (2 + length) + "".join("%*d" % (length, x) for x in range(1, boardX + 1))
My goal here is to print lines from text files together. Some lines, however, are not together like they should be. I resolved the first problem where the denominator was on the line after. For the else statement, they all seem to have the same value/index.
import fitz # this is pymupdf
with fitz.open("math-problems.pdf") as doc: #below converts pdf to txt
text = ""
for page in doc:
text += page.getText()
file_w = open("output.txt", "w") #save as txt file
file_w.write(text)
file_w.close()
file_r = open("output.txt", "r") #read txt file
word = 'f(x) = '
#--------------------------
list1 = file_r.readlines() # read each line and put into list
list2 = [k for k in list1 if word in k] # look for all elements with "f(x)" and put all in new list
list1_N = list1
list2_N = list2
list1 = [e[3:] for e in list1] #remove first three characters (the first three characters are always "1) " or "A) "
char = str('\n')
for char in list2:
index = list1.index(char)
def digitcheck(s):
isdigit = str.isdigit
return any(map(isdigit,s))
xx = digitcheck(list1[index])
if xx:
print(list1[index] + " / " + list1_N[index+1])
else:
print(list1[index] + list1[index+1]) # PROBLEM IS HERE, HOW COME EACH VALUE IS SAME HERE?
Output from terminal:
f(x) = x3 + x2 - 20x
/ x2 - 3x - 18
f(x) =
2 + 5x
f(x) =
2 + 5x
f(x) =
2 + 5x
f(x) =
2 + 5x
f(x) = x2 + 3x - 10
/ x2 - 5x - 14
f(x) = x2 + 2x - 8
/ x2 - 3x - 10
f(x) = x - 1
/ x2 + 8
f(x) = 3x3 - 2x - 6
/ 8x3 - 7x + 4
f(x) =
2 + 5x
f(x) = x3 - 6x2 + 4x - 1
/ x2 + 8x
Process finished with exit code 0
SOLVED
#copperfield was correct, I had repeating values so my index was repeating. I solved this using a solution by #Shonu93 in here. Essentially it locates all indices of duplicate values and puts these indices into one list elem_pos and then prints each index from list1
if empty in list1:
counter = 0
elem_pos = []
for i in list1:
if i == empty:
elem_pos.append(counter)
counter = counter + 1
xy = elem_pos
for i in xy:
print(list1[i] + list1_N[i+1])
I am trying to create this pattern in python:
*
* *
* * *
* *
*
This is my program so far that I've come up with:
ster = "*"
space = " "
lines = 0
n = 3
x = 1
while lines <= 5:
print space*n, ster*x
n-= 1
x+= 1
lines += 1
What am I doing wrong?
Okay, first of all you can create a list of numbers which represents the number of stars in each line.
number_of_stars = 5
i_list = list(range(number_of_stars))
# extend the list by its inverse i_list[::-1]
# but exclude the first item
i_list.extend(i_list[::-1][1:])
print(i_list) # prints: [0, 1, 2, 3, 4, 3, 2, 1, 0]
Now you can go thru the list and print a multiple of *
for i in i_list:
print('* ' * i)
But this is not aligned properly. By adding multiple empty spaces to the left one can archive a solution:
for i in i_list:
print(' ' * (number_of_stars - i) + '* ' * i)
Note that in python one can repeat a string by using the multiplication symbol:
print('a'*5) # prints: aaaaa
Thank you for the help, I wrote a functional code for the problem. It was supposed to made using while loop(s).
This is what I did:
width = int(input("Width: "))
i = 1
while i < width*2:
if i < width:
print " " * (width-i) + "* " * i
else:
print " " * (i-width) + "* " * (2*width-i)
i = i + 1
Notice you have
3 spaces for 1 star
2 spaces for 2 stars
1 space for 3 stars.
For the upright triangle part of your diamond (including the large part). Then you have
2 spaces for 2 stars
3 spaces for 1 star
Without throwing out the answer, try analysing a certain pattern in what i've just pointed out. It can be achieved with 2 loops ( for or while, depending on your preference).
My Code:
infile = open("table1.txt", "r")
a_list = infile.read().split("\n")
infile.close()
for pass_num in range(len(a_list)-1, 0, -1):
for i in range(0, pass_num):
if int(a_list[i].split(",")[1].strip()) > int(a_list[i+1].split(",")[1].strip()):
a_list[i], a_list[i+1] = a_list[i+1], a_list[i]
if (int(a_list[i].split(",")[1].strip()) == int(a_list[i+1].split(",")[1].strip())) and ((int(a_list[i].split(",")[2]) - int(a_list[i].split(",")[3].strip())) > (int(a_list[i+1].split(",")[2].strip()) - int(a_list[i+1].split(",")[3].strip()))):
a_list[i], a_list[i+1] = a_list[i+1], a_list[i]
if (int(a_list[i].split(",")[1].strip()) == int(a_list[i+1].split(",")[1].strip())) and ((int(a_list[i].split(",")[2]) - int(a_list[i].split(",")[3].strip())) == (int(a_list[i+1].split(",")[2].strip()) - int(a_list[i+1].split(",")[3].strip()))):
if (int(a_list[i].split(",")[2])) > int(a_list[i+1].split(",")[2]):
a_list[i], a_list[i+1] = a_list[i+1], a_list[i]
a_list.reverse()
print(" Team" + " "*(30-len(" Team")) + "Points" + " "*2 + "Diff" + " "*4 + "Goals")
for i in range(len(a_list)):
team = a_list[i].split(",")[0]
points = a_list[i].split(",")[1]
goalfor = int(a_list[i].split(",")[2].strip())
goalagainst = int(a_list[i].split(",")[3].strip())
diff = goalfor - goalagainst
print(str(i+1).rjust(2) + ". " + '{0:27} {1:4} {2:4} {3:5} : {4:2}'.format(team, points, diff, goalfor, goalagainst))
#Area of interest above^
Current output:
Desired output:
Would anyone know how to edit the area of interest in the commented piece of code to produce the desired output with the 9's lined up underneath the 3 in 13? Ive been trying .rjust(1) but it wont seem to work.
Python string format support align.
align ::= "<" | ">" | "=" | "^"
'<' Forces the field to be left-aligned within the available space (this is the default for most objects).
'>' Forces the field to be right-aligned within the available space (this is the default for numbers).
'=' Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types.
'^' Forces the field to be centered within the available space.
So use {:>} for right align.
DEMO
>>> print "{}\t{:<2}".format(1, 20)
1 20
>>> print "{}\t{:<2}".format(1, 2)
1 2
>>> print "{}\t{:>2}".format(1, 2)
1 2
>>> print "{}\t{:>2}".format(1, 20)
1 20
In your case, just align the format in the following way:
print(str(1).rjust(2) + ". " + '{0:27} {1:>4} {2:4} {3:5} : {4:2}'.format("adasd", 1, -12, 1, 2))
^^^
I have a list of floating point value, and I'd like to plot it onto a graph. How can we extract the first 4 precision from a floating number, before putting into another new list?
C = []
C.append(23.1234567890)
C.append(14.1234567890)
print ('C - ' + str(C))
D = []
D.append(C[0])
D.append(C[1])
print ('D - ' + str(D))
Got
C - [23.123456789, 14.123456789]
D - [23.123456789, 14.123456789]
Expecting
C - [23.123456789, 14.123456789]
D - [23.1235, 14.1235]
You can get a string representation pretty easily:
>>> '{:.4f}'.format(23.1234567890)
'23.1235'
You can also use the round function:
>>> round(23.1234567890, 4)
23.1235
Note that if you use round, the number will almost never be exactly to the 4 digits of precision that you want due to the representation of floating point numbers.
You can do it, for example, through string manipulation:
strC = split(str(C), ".")
strC = strC[0] + "." + strC[1][:5]
print ('C - ' + strC)
You can do it using string formatting:
C = []
C.append(23.1234567890)
C.append(14.1234567890)
print ('C - ' + str(C))
D = []
D.append(float("%.4f" % C[0]))
D.append(float("%.4f" % C[1]))
print ('D - ' + str(D))
You can mathematically remove the unneeded digits, using the modulo % function:
C = []
C.append(23.1234567890)
C.append(14.1234567890)
print ('C - ' + str(C))
D = []
for i in C:
D.append(i - (i% (10**-4)))
print ('D - ' + str(D))
Where -4 is the number of digits you want to keep. 10**-4 is 0.0001.