Access the same attribute from different objects in Python [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Suppose I have a class called Cube and I create three objects:
class Cube():
def __init__(self, volume):
self.volume = volume
a = Cube(param_a)
b = Cube(param_b)
c = Cube(param_c)
I was wondering if I can write a function, to which the user can give a format, and the function can apply the format to the objects? For example:
>>> print_all(dummy_cube.volume)
a.volume
b.volume
c.volume
So basically the function contains a loop which will replace dummy_cube to a, b, c.
I know I can use something like getattr(), but it has limits. For example, I hope that the function can print whatever format the user gives:
>>> print_all( (dummy_cube.volume)**2 + 1 )
(a.volume)**2 + 1
(b.volume)**2 + 1
(c.volume)**2 + 1
Is there any good way to do this?
Edit: As the comments pointed out, yes the function can take a list, and I intend it to return the numerical values instead of the format itself.
With a list I can do like:
cube_list = [a, b, c]
for cube in cube_list:
print( (cube.volume)**2 + 1 )
But I am still not sure how I can do it with arbitrary expressions given by the user.

The user can supply a function.
def print_all(f):
for cube in cube_list:
print(f(cube))
import operator
print_all(operator.attrgetter('volume'))
print_all(lambda c: c.volume**2 + 1)

Related

Convert variable contents to string in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
This post was edited and submitted for review last month and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I have a variable which has an equation .I'm trying convert the equation that the varibale has into a string and compute the results
Eg
def func1(x):
y = x + 5
return y, 'x+5'
x as input can vary since I'm iterating
through multiple values
Say
h[0][1] = 5
func1(h[0][1])
Output - 10, "h[0][1]+5"
Required result
I need x+5 as string and the computed result of y as a while calling func1
Eval and exec seemed like a probable solution but they perform the inverse of what is needed
I'm not sure I understand why you'd want this but given that the variable holding the equation would be known when coding, you could just wrap the equation in a function. Eg:
def add_five(x):
return (x + 5, "x + 5")
x = 10
y = add_five(x)
print("Answer is", y[0])
print("Equation is", y[1])

Is there a way to plot a "function string" in python? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 months ago.
Improve this question
Example: The user types "(x^2 + 5)^3" into the terminal and the script plots the function like WolframAlpha would do.
Is there an easy way to do that in python?
The function might include abs(), sqrt() etc.
Thanks in advance for your responses
You could try using eval with an inputted X or default x:
import matplotlib.pyplot as plt
import numpy as np
import re
def get_variables(input_string):
count = 0
matches = re.findall(r'(?i)[a-z]', input_string)
return set(matches) #returns unique variables
function = input('Input Function: ')
variables = get_variables(function)
print(variables, type(variables), function)
varDict = {v: np.arange(100) for v in variables} #maps the variable names to some default range
for v in variables: #changes the function string to work with the newly defined variables
pattern = r'\b%s\b' %v
function = re.sub(pattern,r'varDict["%s"]' %v,function)
answer = eval(function) #evaluates the function
if len(variables) == 1:
plt.plot(*varDict.values(),answer) #plot the results, in this case two dimensional
else:
ax = plt.axes(projection="3d")
ax.plot3D(*varDict.values(),answer) # line
#ax.scatter3D(*varDict.values(),answer); #scatter
plt.show()
You can change the 3d settings if you want a scatterplot or add logic to make a shape (ie using meshgrid)
Just be sure that the eval statements are fully sanitized. This also requires the function to be inputted in python syntax (** not ^), unless you want to add functions to edit common syntax differences in the string.

calling functions in for loop - python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
i have a lab for my computer science class and i can't seem to get it right.
we're required to import everything from math and to define functions for geometric shapes
ex:
def triangleArea(b,h):
return b * h / 2
for calling it, we need to make a menu to make the user choose what they want for these geometric shapes. for example, if you chose the number 2 and it gives you the volume of a cylinder.
i just can't seem to understand how you call the function inside the while/for loops.
thank uu~!
def find_area(width, height): # define function
return width * height
for i in range(10):
area = find_area(i, 10) #calls function 'find_area()' and saves returned
#value to variable area
print(area) # prints area
count = 0
while count < 10:
area = find_area(i, 10) #calls function 'find_area()' and save returned
#value to variable area
print(area)
count += 1
Example calling function find_area() from within a for-loop and while-loop.

Finding all possible combinations of sum product to reach a given target [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
There has been a solution to find the possible combination of numbers to reach a given target number. However, I have a different situation below, where a,b, and c are product types and I like to find the combination of sum products of a,b and c to reach the target total.
a = 50sqft
b = 70sqft
c = 100sqft
Total = 5000sqft
I like to find all possible combinations of numbers (integer solution) of a,b,c to get to 5000, and how can I create a python function for that?
Results :
(100a,0b,0c)=5000
(23a,5b,8c)=5000
...
...
Thanks in advance!!
I got a solution :
a=50
b=70
c=100
for i in range(101): # This si 101 here to give 100a=5000
for j in range(100):
for k in range(100):
if i*a + j*b + k*c == 5000:
print('({}a,{}b,{}c)=5000'.format(i,j,k))

shifting numbers in python code [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Please help I have no idea on how to write this function. I tried a ceaser cypher function and it didn't work. Any ideas?
Write a function cycle( S, n ) that takes in a string S of '0's and '1's and an integer n and returns the a string in which S has shifted its last character to the initial position n times. For example, cycle('1110110000', 2) would return '0011101100'.
The function you are looking for is:
def cycle(s, n):
return s[-n:] + s[:-n]
You could use Python's deque data type as follows:
import collections
def cycle(s, n):
d = collections.deque(s)
d.rotate(n)
return "".join(d)
print cycle('1110110000', 2)
This would display:
0011101100

Categories