How do you print variables outside of a class? [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
I am very new to Python. I am currently using Jupyter Notebook and I need to print the variable "pos_best_g" outside of the following class:
class PSO():
def __init__(self,costFunc,x0,bounds,num_particles,maxiter):
global num_dimensions
num_dimensions=len(x0)
err_best_g=-1 # best error for group
pos_best_g=[] # best position for group
# establish the swarm
swarm=[]
for i in range(0,num_particles):
swarm.append(Particle(x0))
# begin optimization loop
i=0
while i < maxiter:
#print i,err_best_g
# cycle through particles in swarm and evaluate fitness
for j in range(0,num_particles):
swarm[j].evaluate(costFunc)
# determine if current particle is the best (globally)
if swarm[j].err_i < err_best_g or err_best_g == -1:
pos_best_g=list(swarm[j].position_i)
err_best_g=float(swarm[j].err_i)
# cycle through swarm and update velocities and position
for j in range(0,num_particles):
swarm[j].update_velocity(pos_best_g)
swarm[j].update_position(bounds)
i+=1
# print final results
print ('FINAL:')
print (pos_best_g)
print (err_best_g)
initial=[5,5,5,5,5] # initial starting location [x1,x2...]
bounds=[(-10,10),(-10,10),(-10,10),(-10,10),(-10,10)] # input bounds [(x1_min,x1_max),(x2_min,x2_max)...]
PSO(func1,initial,bounds,num_particles=15,maxiter=30)
At the moment I get the following result:
FINAL:
[4.999187204673611, 5.992158863901226, 4.614395966906296, 0.7676323454298957, 8.533876878259441]
0.001554888332705297
However, I don't know how to extract the results as they are all within an In[] cell and not an Out[] cell.
What do I need to do to enable this?
Many thanks

There are 2 ways to do this:
1. return "pos_best_g" variable at the end of "init" function.
define a variable before class and define it as global variable inside the class, then change its value at the end of the init
like:
your_new_variable
class PSO():
def __init__(self,costFunc,x0,bounds,num_particles,maxiter):
global num_dimensions
global your_new_variable
...
print ('FINAL:')
print (pos_best_g)
print (err_best_g)
your_new_variable = pos_best_g

Set the result you want to extract as class attributes
class PSO():
def __init__(self,costFunc,x0,bounds,num_particles,maxiter):
...
# Set class attributes
self.pos_best_g = pos_best_g
self.err_best_g = err_best_g
Then you can access it from the object
pso = PSO(func1,initial,bounds,num_particles=15,maxiter=30)
# print final results
print ('FINAL:')
print (pso.pos_best_g)
print (pso.err_best_g)

I am guessing this is your own defined class, right? You can try adding a getter method and later call this method in Jupyter notebook to store the output results in variables as follows:
Just include these small functions inside your class
def get_pos_best(self):
return self.pos_best_g
def get_err_best(self):
return self.err_best_g
Now, inside your notebook do the following:
object_PSO = PSO(costFunc,x0,bounds,num_particles,maxiter)
list_you_want = object_PSO.get_pos_best()
error_you_want = object_PSO.get_err_best()
Good luck!

Related

Parallel Programming - 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 last year.
Improve this question
I have recently heard some things about parallel programming and I know basically nothing about it but will read up on it. But as a start, is it possible to run for instance this code:
for i in range(1000):
print('Process1:', i)
for j in range(1000):
print('Process2:', j)
in parallel? This case is just a toy example but it would help the understanding of the "potential" of parallel programming.
And, if that code can be ran in parallell, will it print out output from both loops in parallell in the following manner:
Process1: 0
Process2: 0
Process1: 1
.
.
.
or what?
Since you are a beginner, the same with threading below:
(Note that the output is not controlled in any way and might mix up!)
import threading
def f1():
for i in range(1000):
print('Process1:', i)
def f2():
for j in range(1000):
print('Process2:', j)
t1=threading.Thread(target=f1)
t2=threading.Thread(target=f2)
t1.start()
t2.start()
Short anser is yes, and how the output will look depends on which method you use.
For example if you want to use concurrent.futures, you can print the output as it is performed inside the function, and order will be scrambled.
If you instead want to access return values, you can chose if you want to access them as they are completed, in whichever order they happen to finish, or you can use the "map" function to retrieve them in the expected order.
import concurrent.futures
def test_function(arguments: tuple):
test_value, function = arguments
"""Print the test value 1000 times"""
for i in range(0, 1000):
print(f"Function {function}, {test_value}, iteration {i}")
return test_value
def main():
"""Main function"""
# Context manager for parallel tasks
with concurrent.futures.ThreadPoolExecutor() as executor:
# Submit example. Executes the function calls asynchronously
result = [executor.submit(test_function, (i, "submit")) for i in range(1, 21)]
# Map example.
# Takes an iterable as argument that will execute the function once for each item
result_2 = executor.map(test_function, [(i, "map") for i in range(1, 21)])
for future in concurrent.futures.as_completed(result):
print(f"Submit: Process {future.result()} completed")
for future in result_2:
print(f"Map: Process {future} completed")
if __name__ == '__main__':
main()

Confused about how the return works in python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
The program runs and the function works but I am not able to see my docCountryList in the output. Can someone tell me why?
I have this code
def ViewByCountry(docID,user_selection):
docCountryList=[]
for x in jfile:
if x.get('subject_doc_id') == docID:
docCountryList.append(x['visitor_country'])
if user_selection == '2a':
x = []
y = []
#Insert countries and number of occurences in two seperate lists
for k,v in Counter(docCountryList).items():
x.append(k)
y.append(v)
plt.title('Countries of Viewers')
plt.bar(range(len(y)), y, align='center')
plt.xticks(range(len(y)), x, size='small')
plt.show()
return docCountryList
and in my main
from program import ViewByCountry
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
docID = input("Enter required document ID: ")
user_selection = input("Enter selection")
ViewByCountry(docID,user_selection)
You never print out the value of docCountryList, so try this:
print(ViewByCountry(docID,user_selection))
This will print out the value.
You can do this as well:
lst = ViewByCountry(docID,user_selection)
print(lst)
In your main you can change to myView = ViewByCountry(docID,user_selection) and then add print(myView). This saves the list created by your function to a variable to be printed or used later.

How to have a function feed another function's input [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 2 years ago.
Improve this question
I'm making a hangman game and testing how different letter picking algorithms fare, but to do this, the guessing algorithm function has to feed a letter into the hangman function's input('Select a letter').
How do you make it so that a function detects when another function is waiting for an input ?
Assuming you are doing input() in a loop inside your hangman function, you could switch that to a yield and let an external function drive input as needed. In this example I have a hangman function that uses yield to get data. Now its a generator and driving function can use next and the generator's .send method to pump data into it.
def hangman(chances=5):
for i in range(chances):
letter = yield "prompt"
if letter == "quit":
yield "quit"
return
print("letter", letter)
# do all the things
solved = False
if solved:
yield "solved"
yield "failed"
def command_line_prompt_hangman():
feeder = hangman()
state = next(feeder)
while state == "prompt":
state = feeder.send(input("Next letter: "))
def test():
# after years of testing the best algorithm is
test = ['a', 'b', 'c', 'd', 'e', 'f']
feeder = hangman()
assert next(feeder) == "prompt"
for count, letter in enumerate(test, 1):
state = feeder.send(letter)
if state == "solved":
print("did it in ", count, "tries")
break
if state == "failed":
print("exceeded count")
break
command_line_prompt_hangman()
test()
Instead of using the input function, write a custom function to pull an output from whatever algorithm you are using. That would look something like this:
user_input = algo_obj.get_input(game_state)
In this case, algo_obj would be an object storing the current state of the algorithm/generator (if such a state exists, otherwise you can just call the function normally). game_state would be some representation of the game's current state (available letters, the word-form -- ie. blanks & letters).
You can then feed user_input to your Hangman function.
This should be as simple as:
Define both functions.
Pass one function return value to the other one as argument.
This can be done by using input() as according to this
e.g. Define the functions
def first_function():
input_variable = input("Please enter some data")
return input_variable
def second_function(a):
print(a) # Do some calculations here
And use them:
second_function(first_function())
I wouldn't say that this is necessarily the best way to go about but it solves Your problem. If You would like to receive a more detailed answer please provide code samples.

Unresolved Reference - Python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a function that takes a string input. I want to count no of times a string occurs in the input.
Example, I have a string cars = "Toyota, Honda, Toyota, BMW, Toyota"
I want a function that returns no of times a string occur
toyota_count = 0
honda_count = 0
BMW_count = 0
def count_cars(cars):
if "toyota" in cars:
toyota_count += 1
if "honda" in cars:
honda_count += 1
But this gives me error on toyota_count in the function, it says "Unresolved reference toyota_count"
Its because toyota_count is global.
Either define the variable inside your method (preferred) or specify it inside your methot as global like so:
def myfunc():
gobal toyota_count
EDIT
You can also just use cars.count("Toyota") to get the total number of substrings in a string.
Assuming your strings don't overlap, just use the string count() method. Whilst this isn't uber-efficient (three calls to count() and therefore 3 searches) it fits your described use case.
cars = "Toyota, Honda, Toyota, BMW, Toyota"
toyota_count = cars.count("Toyota")
honda_count = cars.count("Honda")
toyota_count = 0
honda_count = 0
BMW_count = 0
def count_cars(cars):
global toyota_count
toyota_count = cars.count('Toyota')
count_cars("Toyota, Honda, Toyota, BMW, Toyota")
print (toyota_count)

getting variable from the constructor [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I try to write a program and get a variable from a constructor to a method but I don't know how to do it :( I get an error with p.liczba in the method sprawdz. I would like to have here a number from the user. The same situation is with p.wielokrotnosc. I know that I can write this program easier but I really would like to learn OOP with simple examples like this
class Przyklad:
def __init__(self, liczba):
self.liczba = liczba
def podajSzukana(self):
self.wielokrotnosc = 3
class Dane:
def wczytaj(self):
a = int(input('Podaj mi liczbę '))
p = Przyklad(a)
def sprawdz(self):
if (p.liczba % p.wielokrotnosc == 0):
return true
print ('Witaj w programie szukającym wielokrotność liczby 3 \n')
d = Dane()
d.wczytaj()
d.sprawdz()
The problem is not getting the variable from the constructor of Przyklad. The problem is saving it in Dane. The common procedure is to attach it to instance of Dane:
def wczytaj(self):
a = int(input('Podaj mi liczbę '))
self.p = Przyklad(a)
Then, you'll have self.p available in Dane
This is happening because the variable liczba is contained within the class Przyklad, so when you try to access it in Dane, it is not possible.
You should try having liczba be a global variable (which is dangerous), or having Dane be a descendant of Przyklad (these names though....).
a and p are local variables not members of Dane. You have to use self. (as pointed by jonrsharpe) to be able to access this variable from the class context:
class Dane:
def wczytaj(self):
a = int(input('Podaj mi liczbę '))
self.p = Przyklad(a)
def sprawdz(self):
if (self.p.liczba % self.p.wielokrotnosc == 0):
return true
Another issue is that self.wielokrotnosc do not exists until you call podajSzukana(self) method. One way to fix this is calling that function inside your constructor:
class Przyklad:
def __init__(self, liczba):
self.liczba = liczba
self.podajSzukana() // Call the method here.
def podajSzukana(self):
self.wielokrotnosc = 3

Categories