Getting a particular value from a function - python

I am trying to extract a particular value from a function which deals with multiple values.
My simplified example:
def func(x, y):
a = ran(0,10) #creates random integer
b = ran(0,10)
return a*x + b*y
print a*x + b*y
So if I want to use the values of a and b that get created in func() in some other function, how would I extract them?

It's not so much that you need to extract them; you just need to save them somewhere.
If this is a top-level function in a module, consider a module variable:
import random
rand1 = random.randint(0, 10)
rand2 = random.randint(0, 10)
def f(x, y):
result = rand1*x + rand2*y
print result
return result
but these look suspiciously related so perhaps they belong in a class?
class YourClass(object):
def __init__(self):
self.rand1 = random.randint(0, 10)
self.rand2 = random.randint(0, 10)
def your_func_as_a_method(self, x, y):
result = self.rand1*x + self.rand2*y
print result
return result
Of course, you could also just make them part of the function's return definition:
def f(x, y):
rand1 = random.randint(0, 10)
rand2 = random.randint(0, 10)
result = rand1*x + rand2*y
print result
return (result, rand1, rand2)
fxy, a, b = f(x, y)

One way is to return them:
return (a*x + b*y, a, b)
and you can call your function as:
(result, a, b) = func(x,y)

Related

How can i pass a requirement into a sort function, and create a template sort method to either sort one of the object of class "reading" in python

#i want to pass the list, and algorithm (bubblesort) into the sort method with a requirement (temp or wind_speed)
class Reading:
def __init__(self, _temperature, _windspeed):
self.temp = _temperature
self.windspeed = _windspeed
def bubblesort(num):
for i in range (len(num)-1, 0, -1):
for j in range (i):
if num[j] > num [j+1] :
temp = num[j]
num[j] = num[j+1]
num[j+1] = temp
return num
r_list = [Reading(randint(10, 60), randint(10, 60)) for i in range(20)]
def sort(lst, alg): #how do i pass the requirement, and alg?
bubblesort(lst)
sort(r_list, alg) #how do i create a templated bubblesort to either sort temp or windspeed?
#The Output is supposed to return a sorted list (r_list) according to the requirement
Here's an example how to pass a function as an argument to another function:
def add(x, y):
return x + y
def mul(x,y):
return x * y
def calculate(x, y, func):
return func(x, y)
z1 = calculate(1, 1, add)
z2 = calculate(1, 1, mul)
print(f"add = {z1}, mul = {z2}")

Im trying to calculate cartesian distance between two points using classes

import random
class point:
def __init__(self,p):
self.p = p
def fill_point(self):
x = random.uniform(0,100)
y = random.uniform(0,100)
z = random.uniform(0,100)
self.p = [x,y,z]
return self.p
def distance_between_points(self,p1,p2):
D = ((self.p1[0]-self.p2[0])**2 + (self.p1[1]-self.p2[1])**2 + (self.p1[2]-self.p2[2])**2)**(1/2)
return D
def main():
point1 = point(fill_point())
point2 = point(fill_point())
Distance = distance_between_points(point1,point2)
print(Distance)
main()
im quite new to classes and am having a hard time understanding what im doing wrong.
import random
from math import sqrt
class Point:
def __init__(self, name='anonym_point',x=0,y=0,z=0):
self.name = name
self.x = x
self.y = y
self.z = z
#property
def coord(self):
return (self.x, self.y, self.z)
def __repr__(self):
return ("{} has coordinate {}  {}  {}".format(self.name, self.x, self.y, self.z))
def makepoint(namepoint):
return Point(namepoint, random.uniform(0,100), random.uniform(0,100), random.uniform(0,100))
def distance_between_points(p1,p2):
dist = sqrt((p2.x-p1.x)**2 + (p2.y-p1.y)**2 + (p2.z-p1.z)**2)
print("distance between point ",p1.name," and the point ",p2.name," : ",dist)
point1 = makepoint("p1")
point2 = makepoint("p2")
print(point1)
print(point2)
Distance = distance_between_points(point1,point2)
The issue is that you are accessing the class method just as a normal method, you need to initialize class object first then call the method by class object you created, again use only the variables you are sure you need,. keeping code easy for you because I think you already know what you needed I did this
import random
class Point:
def fill_point(self):
x = random.uniform(0,100)
y = random.uniform(0,100)
z = random.uniform(0,100)
p = [x,y,z]
return p
def distance_between_points(self,p1,p2):
D = ((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2 + (p1[2]-p2[2])**2)**(1/2)
return D
def main():
obj = Point()
point1 = obj.fill_point()
point2 = obj.fill_point()
distance = obj.distance_between_points(point1,point2)
print(distance)
main()
it would not kill if you try to understand python classes better, python best naming, etc...
i think that what you are trying to do is something like this.
import math
class Point():
def __init__(self,x,y,z):
self.coordinates = (x,y,z)
def distance(self,point):
return math.sqrt((point.coordinates[0] - self.coordinates[0])**2 + (point.coordinates[1] - self.coordinates[1])**2 + (point.coordinates[1] - self.coordinates[1])**2)
a = Point(4,2,8)
b = Point(2,7,3)
print(a.distance(b))
what you are doing by executing this python code is simply creating a "Point" class, this point class has an attribute (coordinates) that contains its coordinates into a tuple.
so to create a point object you just have to use this code point = Point(x_coordinates,y_coordinates,z_coordinates).
In the last line the code calculates the distance between two points, in that case you are calculating the distance of "b" respect to "a", but you could also do viceversa by doing something like this: print(b.distance(a))
to calculate the distance between random point all you have to do is this:
import math, random
class Point():
def __init__(self,x,y,z):
self.coordinates = (x,y,z)
def distance(self,point):
return math.sqrt((point.coordinates[0] - self.coordinates[0])**2 + (point.coordinates[1] - self.coordinates[1])**2 + (point.coordinates[1] - self.coordinates[1])**2)
r = lambda: random.uniform(0,100)
a = Point(r(),r(),r())
b = Point(r(),r(),r())
print(a.distance(b))
this is how to do that, but i really don't understand why you should calculate the distance between two random numbers

how to make a temporary object from withing the class function in python?

I'm writing this code and there is a need to send objects as parameters in functions. My problem is one of the objects needs to be resued with its original values but as I need to return an object from the functions.
I don't know how I can send the answer and keep the original values in the object
safe for reuse. Is there any way to make an object from the class declaration itself?
import math
class Points(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __sub__(self, no):
no.x = no.x - self.x
no.y = no.y - self.y
no.z = no.z - self.z
return(no)
def dot(self, no):
ans = (self.x * no.x)+(self.y * no.y)+(self.z * no.z)
return ans
def cross(self, no):
x = (self.y * no.z)-(self.z * no.y)
y = (self.x * no.z)-(self.z * no.x)
z = (self.x * no.y)-(self.y * no.x)
self.x = x
self.y = y
self.z = z
return(self)
def absolute(self):
return pow((self.x ** 2 + self.y ** 2 + self.z ** 2), 0.5)
if __name__ == '__main__':
points = list()
for i in range(4):
a = list(map(float, input().split()))
points.append(a)
a, b, c, d = Points(*points[0]), Points(*points[1]), Points(*points[2]), Points(*points[3])
x = (b - a).cross(c - b)
y = (c - b).cross(d - c)
angle = math.acos(x.dot(y) / (x.absolute() * y.absolute()))
print("%.2f" % math.degrees(angle))
I want to do something like:
def function_name(self,other)
temp.x = self.x + other.x
temp.y = self.y + other.y
return temp
This way both input objects will have their original values but I don't know how to get that temp.
Thanks everyone who helped. I got the answer to what I was looking. I wanted an object to act as a container that can store the class variables,
and I didn't knew I can just make a new object of the class from within it!
import math
class Points(object):
def __init__(self, x, y, z):
self.x=x
self.y=y
self.z=z
def __sub__(self, no):
return Points((self.x-no.x),(self.y-no.y),(self.z-no.z))
def dot(self, no):
return (self.x*no.x)+(self.y*no.y)+(self.z*no.z)
def cross(self, no):
return Points((self.y*no.z-self.z*no.y),(self.z*no.x-self.x*no.z),(self.x*no.y-self.y*no.x))
def absolute(self):
return pow((self.x ** 2 + self.y ** 2 + self.z ** 2), 0.5)
As you can see using points, i.e the constructor for class Points, I can store the result of any operations and can return it as an object while not altering my input objects.
If what you're trying to do is reuse a variable that you have passed to a class object, you can just duplicate it in your __init__ statement, or in the function where you use it.
e.g
class Foo:
def __init__(self, my_var1, my_var2):
self.my_var1 = my_var1
self.my_var2 = my_var2
def bar(self):
bar_var1 = self.my_var1
bar_var2 = self.my_var2
bar_var1 = bar_var1 + bar_var2
return bar_var1
Although, I am a little confused by why you are attempting to return self in your cross function, as self is a class parameter, and you don't seem to be using it in its intended purpose. If you're confused about how you should be using self, a brief read through the python class tutorial might be helpful. However, barring that, I hope this answers your question.

Values not visible when printing list of objects

Totally rewritten code:
HOR = [0, 1, 3, 6]
VER = [0,10,20,100,1000]
class Pos:
def __init__(self, x, y):
if (x in HOR) and (y in VER):
self.x = x
self.y = y
else:
print "Invalid position: ", x, y
def __str__(self):
return self.x + self.y
def get_x(self):
return self.x
def get_y(self):
return self.y
class list_A1:
def __init__(self): # create a A1 object
self.list_A1 = []
for i in HOR:
for j in VER:
self.list_A1.append(Pos(i,j))
def __str__(self):
d = "list_A1 contains: " + repr(self)
return d # return a string representing the A1
a1 = list_A1()
print a1
Now I get:
list_A1 contains: <__main__.list_A1 object>
but I want to get list of [x,y], for example:
[[1,1],[1,2]...]
I am new to object programming and I don't understand why I can't see these values in the list.
The parentheses after self.A1 mean that you are trying to call it as if it were a function. As the error message tells you, you cannot call a list. The correct syntax would be:
d = "A1 contains: " + str(self.A1)
or, better
d = "A1 contains: {}".format(self.A1)
Also, you seem to be using A1 (the class name) and A (the instance attribute) interchangeably; you should give your classes, attributes and methods more sensible and meaningful names to help avoid this issue.
Do
self.A.append(Pos(x,y))
instead of
self.A1.append(Pos(x,y))
and
d = "A1 contains: " + str(self.A)
Edit:
Implement str(self) and repr(self) of Pos if you want to print them.
A1.A1 is not defined in your code example. If it is a list, just change the line to:
d = "A1 contains: " + str(self.A1)

Debugging Python Program LCM

So I have this program:
def gcd(x, y):
while y % x != 0:
y = y % x
x = x % y
return y
def lcm(x, y):
(x * y) / gcd(x, y)
a = lcm(1, 2)
b = lcm(3, a)
c = lcm(b, 4)
d = lcm(5, c)
e = lcm(6, d)
f = lcm(e, 7)
g = lcm(f, 8)
h = lcm(9, g)
i = lcm(h, 10)
j = lcm(11, i)
k = lcm(12, j)
l = lcm(k, 13)
m = lcm(l, 14)
n = lcm(15, m)
o = lcm(n, 16)
p = lcm(17, o)
q = lcm(18, p)
r = lcm(q, 19)
print(lcm(r, 20))
Ok, so I've worked that one out now thanks to answers on this post, but why does this:
def gcd(x, y):
while y % x != 0:
y = y % x
x = x % y
return y
def lcm(x, y):
return (x * y) / gcd(x, y)
a = lcm(1, 2)
b = lcm(3, a)
c = lcm(b, 4)
d = lcm(5, c)
e = lcm(6, d)
f = lcm(e, 7)
g = lcm(f, 8)
h = lcm(9, g)
i = lcm(h, 10)
j = lcm(11, i)
k = lcm(12, j)
l = lcm(k, 13)
m = lcm(l, 14)
n = lcm(15, m)
o = lcm(n, 16)
p = lcm(17, o)
q = lcm(18, p)
r = lcm(q, 19)
print(lcm(r, 20))
return this:
ZeroDivisonError: float modulo
Complaining about the second line, I gather I might need some sort of if statement to put the two numbers in order.
Anyone got any information about why this is happening?
Thanks.
You forgot to return something in the lcm function.
def lcm(x, y):
return (x * y) / gcd(x, y)
When you don't explicitly return anything in a function, Python automatically returns None. When you try lcm(r, 20), that's the same as lcm(None, 20), which doesn't work since you multiply both parameters in the lcm function - you can't do None * 20.
However this will yield another error - there's a problem with your gcd function as well!
The error comes when y % x is 0, and then you do x % y straight after. This would be a working solution:
def gcd(x, y):
while y != 0:
x, y = y, x % y
return x
This is taken straight from Euclid's algorithm from the Wikipedia article (Section 2.2).
There is a misunderstanding here.when you use gcd() inside lcm(), you are creating nested environments. gcd()'s environment doesn't have access to the global environment.anything that it returns, will be accessible by lcm()'s environment.you don't return anything to the global environment in lcm(), so python by default returns None.to fix this try:
def lcm(x, y):
return (x * y) / gcd(x, y)
also you have to add this block to the lcm() to avoid throwing ZeroDivision exception:
def lcm(x, y):
try:
return (x * y) / gcd(x, y)
except ZeroDivisionError:
do whatever you want and return a value

Categories

Resources