Can't Assign to Function Call (Python) - python

I have the following code:
class Quadratic:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def function(self, x):
self.F(x) = a*(x**2) + b*x + c
return F(x)
def table(self, lower, upper, varz):
inc = np.absolute(upper-lower) / varz
print inc
for i in range(0 , varz - 1):
self.F(lower)
lower = lower + inc
#lower bound,upper bound, number of values
def roots():
x1 = (-b + math.sqrt(b**2 - 4*a*c)) / (2*a)
x2 = (-b - math.sqrt(b**2 - 4*a*c)) / (2*a)
return x1, x2
def dump(self):
print self.n
Whenever I try and run this script, I get the following:
line 15
self.F(x) = a*(x**2) + b*x + c
SyntaxError: can't assign to function call
Any help or ideas would be greatly appreciated.

It is not clear (to me at least) what it is you're trying to achieve, but perhaps it is as simple as this:
def F(self, x):
return self.a * (x ** 2) + self.b * x + c

As you might have guessed, F(x) is a function call. You're calling the function F, which does not actually exist, passing it the argument x, which does not actually exist either. You need to give your variables legal names, like f_of_x.

try with:
def __init__(self, a,b,c):
self.a = a
self.b = b
self.c = c
self.F = lambda x: a*(x**2)+b*x+c
and discard the function() method

Related

Class Point\Inheritance - task check

I'm trying to solve the tasks (text below), but I have a problem with the second point, i.e. method in it that displays the length of the segment and the positions of the start and end points.-
I don't really know how to write it, Could someone look at the code and give some hints?
Define a Point class with x, y fields and a method displaying the
point's position (eg "point (2,3)").
Then create a class Segment that will inherit from the class point.
Create a method in it that displays the length of the segment and the
positions of the start and end points.
Then define the Triangle class which will contain 3 Points,
automatically determined 3 Sections (walls) of them and included a
method for displaying the surface area of the perimeter.
code:
from math import sqrt, hypot
class Point:
def __init__(self, x_init, y_init):
self.x = x_init
self.y = y_init
def __str__(self):
return "Point(%s,%s)"%(self.x, self.y)
class Segment(Point):
def distance(self): **!-probably a badly written method**
return ((self.x ** 2) + (self.y ** 2)) ** 0.5
def position(self, p): **!-probably a badly written method**
dx = self.x - p.X
dy = self.y - p.Y
return hypot(dx, dy)
class Triangle(Point):
def __init__(self, x, y, z):
Point.__init__(self, x, y)
self.z = z
def __str__(self):
return "Point(x %s ,y %s, z %s )" % (self.x, self.y, self.z)
def __area__(a, b, c):
s = (a + b + c) / 2
return (s * (s - a) * (s - b) * (s - c)) ** 0.5
def __perimeter__(a, b, c):
s = (a + b + c)
return s
Task 2 is just wrong. Segment needs to contain 2 points, so it can't inherit from Point. It should be:
class Segment:
def __init__(self, start, end):
self.start = start
self.end = end
def distance(self):
dist = ((self.start.x - self.end.x) ** 2 + (self.start.y - self.end.y) ** 2) ** 0.5
print(f"distance from {self.start} to {self.end} is {dist}"

Errors in a class when trying to call it

I have this code consisting of a class and a subclass. The class is Euler forward, while the second one is Eulers midpoint method. These are for solving an ODE (x'=x(1/2-x)). Now it doesn't seem to work because when I am to call the function, by typing:
Euler=H.solve(6)
where the 6 is the amount of steps, I get attributeerror.
AttributeError: 'int' object has no attribute 'size'
Could anyone help me make my code more robust and working so I could plot the values later on, really don't see whats wrong. My code below:
import numpy as np
class H:
def __init__(self, f):
self._f = f
def initial(self, u0):
self._u0 = u0
def solve(self, time_points):
n = time_points.size
self._t = time_points
self._u = np.zeros(n)
self._u[0] = self._u0
for k in range(n-1):
self._k = k
self._u[k+1] = self.advance()
return self._u, self._t
class F(H):
def ad(self):
u = self._u; t = self._t; f = self._f; k = self._k
dt = t[k+1] - t[k]
u_k12 = u[k] + dt/2 * f(u[k], t[k])
return u[k] + dt * f(u_k12, (t[k] + dt/2) )
I think what's wrong is the way you use the class. Initial value is set with initial method (u0), then you give solve method the list of points. You can use np.linscape to generate midpoint.
np.linspace(0, 3, 31) # 30 points evenly spaced between 0 and 3
So it's like this:
def func(x, y):
return x * y
midpoint = np.linspace(0, 3, 31)
F_ = F(func)
F_.initial(6)
F_.solve(midpoint)
Code:
class H:
def __init__(self, f):
self._f = f
def initial(self, u0):
self._u0 = u0
def solve(self, time_points):
n = time_points.size
self._t = time_points
self._u = np.zeros(n)
self._u[0] = self._u0
for k in range(n-1):
self._u[k+1] = self.advance(k)
return self._u, self._t
def advance(self, k):
....
class F(H):
def advance(self, k):
dt = self._t[k+1] + self._t[k]
u_k12 = self._u[k] + dt/2 * self._f(self._u[k], self._t[k])
return self._u[k] + dt * self._f(u_k12, (self._t[k] + dt/2))

Python function return value reuse in another fuction

def function1(a,b,c):
total_function1 = a + b + c
return total_function1
def function2():
total_function2 = total_function1 * 0.3
return total_function2
def function3():
total_function3 = total_function1 * 0.7
return total_function3
I am trying to have the logic into the first function and create simple function to just apply some percentage 30% and 70%. I will use the 3 different results into specific sqlite columns.
I have search but was not able to find this specific case.
You need to call the function.
def function1(a,b,c):
total_function1 = a + b + c
return total_function1
def function2(a, b, c):
total_function2 = function1(a, b, c) * 0.3
return total_function2
def function3(a, b, c):
total_function3 = function1(a, b, c) * 0.7
return total_function3
or you could call it outside, and pass the value in:
def function1(a,b,c):
total_function1 = a + b + c
return total_function1
def function2(total_function1):
total_function2 = total_function1 * 0.3
return total_function2
def function3(total_function1):
total_function3 = total_function1 * 0.7
return total_function3
val1 = function1(1, 2, 3)
val2 = function2(val1)
val3 = function3(val1)

Moving function/method to class

Using pycharm, I wish to refactor methods into a class. (Staticmethod would do)
Current:
import math
class Solver(object):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def demo(b, a, c):
d = b ** 2 - 4 * a * c
if d >= 0:
disc = math.sqrt(d)
root1 = (- b + disc) / (2 * a)
root2 = (- b - disc) / (2 * a)
print(root1, root2)
return root1, root2
else:
raise Exception
s = Solver(2, 123, 0.025)
demo(s.b, s.a, s.c)
Desired:
import math
class Solver(object):
def __init__(self,a,b,c):
self.a = a
self.b = b
self.c = c
def demo(self, a, b, c):
d = self.b ** 2 - 4 * self.a * self.c
if d >= 0:
disc = math.sqrt(d)
root1 = (- self.b + disc) / (2 * self.a)
root2 = (- self.b - disc) / (2 * self.a)
print(root1, root2)
return root1, root2
else:
raise Exception
Solver(2, 123, 0.025).demo()
I am basically trying to get the opposite functionality to:
"Moving function/method to the top-level"
as described here:
https://www.jetbrains.com/help/pycharm/2017.1/move-refactorings.html
I wouldn't mind on settling for a class with no init params.
By default there is no such option: PyCharm is quite good at refactoring classes and methods, but can't do much with standalone functions.
Though, there is a solution for your problem: regex!
Basically, what you have to do is:
Change function to bounded method (you already did that in your example)
Replace all occurrences of old method call with refactored one.
Here is the regex which would let you do that for aforementioned example:
([\w]+)[ \t]+=[ \t](Solver[ \t]*\(([\d.]+)[ \t]*,[ \t]*([\d.]+)[ \t]*,[ \t]*([\d.]+)[ \t]*\))\n\r?demo[ \t]*\(\1\.b[ \t]*,[ \t]*\1\.a[ \t]*,[ \t]*\1\.c[ \t]*\)
And here is the replacement:
$2\.demo()
Now you can select Edit -> Find -> Replace in Path in PyCharm, check regex option, paste first regex to first field and second to next one. I've tested that locally with one file and it worked well. And here is regex101 example so you can play with it and test it.
This would be useful if you have a lot of usages of that method, otherwise it could be faster to do that manually.

Python Quadratic Equation Class

I am currently creating a class in python to make a quadratic equation. I wrote down a discriminant function within the class, and I'm trying to call on it within the roots function, however, I'm not sure how to do it for certain. I am getting an attribute error.
AttributeError: 'QuadraticEquation' object has no attribute 'discrimiant'
def discriminant(self):
return ((self.b)**2) - (4 * self.a * self.c)
def root1(self):
if self.discrimiant() < 0:
return None
else:
return (-self.b + math.sqrt(self.discriminant())) / (2 * self.a)
def root2(self):
if self.discrimiant() < 0:
return None
else:
return (-self.b - math.sqrt(self.discriminant())) / (2 * self.a)
There is a spelling mistake in your code. discriminant, not discrimiant. Here is a working code -
class QuadraticEquation:
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def discriminant(self):
return ((self.b)**2) - (4 * self.a * self.c)
def root1(self):
if self.discriminant() < 0:
return None
else:
return (-self.b + math.sqrt(self.discriminant())) / (2 * self.a)
def root2(self):
if self.discriminant() < 0:
return None
else:
return (-self.b - math.sqrt(self.discriminant())) / (2 * self.a)
a = QuadraticEquation(1,2,3)
print a.root1()
print a.root2()
print a.discriminant()

Categories