Unresolved Reference - Python [closed] - python

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)

Related

Can't print an object outside a function [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 1 year ago.
Improve this question
I'm making a simple program in order to compare the currentdate to another date, and I need to separate the "/" and remove trailing zeros; I made a function for that:
def correctdate(compare, Dayslist, Monthslist):
for day in compare:
if day == "/" or day == "\\":
compare.remove(day)
break
else:
Dayslist.append(day)
for removenum in Dayslist:
#* Removing the numbers from the list
compare.remove(removenum)
for month in compare:
Monthslist.append(month)
#* Joining the numbers into a string
correctdate.DaysLeft = "".join(Dayslist)
correctdate.MonthsLeft = "".join(Monthslist)
#* Stripping leading zeros
correctdate.DaysLeft = correctdate.DaysLeft.lstrip("0")
correctdate.MonthsLeft = correctdate.MonthsLeft.lstrip("0")
return
The code works just fine but i want to save the DaysLeft, Monthsleft to print it/edit it ETC..
so i do this:
correctdate(compare,Dayslist,Monthslist)
print(correctdate.Daysleft)
and i get this:
AttributeError: 'function' object has no attribute 'Daysleft'
There was a typo in printing the object attribute
I wrote:
print(correctdate.Daysleft)
Its supposed to be:
print(correctdate.DaysLeft)
Sorry for the inconvenience
You ve to return it in your function, and outside it get it into variables:
def correctdate(compare, Dayslist, Monthslist):
for day in compare:
if day == "/" or day == "\\":
compare.remove(day)
break
else:
Dayslist.append(day)
for removenum in Dayslist:
#* Removing the numbers from the list
compare.remove(removenum)
for month in compare:
Monthslist.append(month)
#* Joining the numbers into a string
correctdate.DaysLeft = "".join(Dayslist)
correctdate.MonthsLeft = "".join(Monthslist)
#* Stripping leading zeros
correctdate.DaysLeft = correctdate.DaysLeft.lstrip("0")
correctdate.MonthsLeft = correctdate.MonthsLeft.lstrip("0")
return correctdate.DaysLeft,correctdate.MonthsLeft
This for return outside function, now you ve to call function correctly:
DaysLeft,Monthsleft = correctdate(compare,Dayslist,Monthslist)
print(DaysLeft,Monthsleft)
Anyway this code "correctdate.MonthsLeft" looks like you want use class and not only functions, so you should use like that https://www.w3schools.com/python/python_classes.asp
def correctdate(compare, Dayslist, Monthslist):
You declare a function with name correctdate that accepts 3 parameters.
correctdate.DaysLeft = "".join(Dayslist)
correctdate.MonthsLeft = "".join(Monthslist)
Then you try to assign a value to a function, which is not possible because correctdate is not a variable, not an object. You just declared it as a function.
What are you trying to achieve?

How do you print variables outside of a class? [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 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!

Why does my while loop not stop? [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 5 years ago.
Improve this question
RANDOM_COR=random.randrange(5,6)
def check_xy_data():
global COUNT
COUNT=0
input_xy=input("input(x,y) : ")
think_xy=list(map(int,input_xy.split(",")))
if(random_array[think_xy[0]][think_xy[1]] == "C"):
screen_array[think_xy[0]][think_xy[1]] = "O"
COUNT=COUNT+1
else:
screen_array[think_xy[0]][think_xy[1]] = "X"
def main():
make_intro()
init_screen_array ()
init_random_array ()
make_random_num(RANDOM_COR)
while(True):
check_xy_data()
draw_outline_start(TOTAL_COL_NUM//2)
draw_out_rowline(TOTAL_COL_NUM//2, "Input : ")
draw_out_rowline(TOTAL_COL_NUM//2, "Correct : ")
draw_out_rowline(TOTAL_COL_NUM//2, "Error : ")
draw_out_rowline(TOTAL_COL_NUM//2, "Total : ")
draw_outline_mid(TOTAL_COL_NUM//2)
if(COUNT==RANDOM_COR-1):
break
The if at the bottom of my code is supposed to get me out of the while loop, but I'm stuck in an infinite loop. Help?
(assignment, 2016) 예고편 The Assignment | 어싸인먼트 감독: 월터 힐 각본: 월터 힐, 데니스 해밀 출연: 김성훈 출연 현빈, 유해진, 김주혁 개봉 2016 한국 상세보기 그간...
Try this change:
RANDOM_COR=random.randrange(5,6)
COUNT = 0
def check_xy_data():
global COUNT
With COUNT inside check_xy_data, you set it back to 0 on every call. It can never reach more than 1. Your check is whether it's in the range 5-6. This is never true, so you can never leave the loop.
Note that trivial debugging skills would have found this: just stick a print statement before you test your loop condition, to see what the values are. Use that next time ... :-)

Can't return a dictionary from my function [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
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.
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.
Improve this question
I am getting an invalid syntax error
SyntaxError: invalid syntax
root#collabnet:/home/projects/twitterBot# python twitterBot2.py
File "twitterBot2.py", line 58
return screenNames
when returning a dictionary from this function:
def getUserName(lookupIds):
l = len(lookupIds) # length of list to process
i = 0 #setting up increment for while loop
screenNames = {}#output dictionary
count = 0 #count of total numbers processed
print 'fetching usernames'
while i < l:
toGet = []
toAppend = []
if l - count > 100:#blocks off in chunks of 100
for m in range (0,100):
toGet.append(lookupIds[count])
count = count + 1
print toGet
else:#handles the remainder
print 'last run'
r = l - count
print screenNames
for k in range (0,r):#takes the remainder of the numbers
toGet.append(lookupIds[count])
count = count + 1
i = l # kills loop
toAppend = api.lookup_users(user_ids=toGet)
print toAppend
screenNames.append(zip(toGet, toAppend)
#creates a dictionary screenNames{user_Ids, screen_Names}
#This logic structure breaks up the list of numbers in chunks of 100 or their
#Remainder and addes them into a dictionary with their count number as the
#index value
#print str(len(toGet)), 'screen names correlated'
return screenNames
I am running the function like so:
toPrint = {}#Testing Only
print "users following", userid
toPrint = getUserName(followingids)#Testing Only
I have tried commenting out and just printing screenNamesand I still get the same error except on the print statement instead. I am pretty sure I am running the return right thanks for the look.
You forgot a closing parenthesis on a preceding line:
screenNames.append(zip(toGet, toAppend)
# ^ ^ ^^?
# | \---- closed ---/|
# \----- not closed ---/
You'll have another problem here, as screenNames is a dict object, not a list, and has no .append() method. If you wanted to update the dictionary with key-value pairs, use update() instead:
screenNames.update(zip(toGet, toAppend))

How to rewrite the code more elegantly [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
The code below reads lines from a file, then it executes the custom function (My_Function) and return values to the variables(e.g. condition_A)
for line in input_file:
if condition_A:
condition_A = My_Function(A_tuple[0], B_tuple[0])
if condition_B:
condition_B = My_Function(A_tuple[1], B_tuple[1])
if condition_C:
condition_C = My_Function(A_tuple[2], B_tuple[2])
if condition_D:
condition_D = My_Function(A_tuple[3], B_tuple[3])
if condition_E:
condition_E = My_Function(A_tuple[4], B_tuple[4])
...
My question is: can the code be modified to more elegant version? After all, many code is similar(I don't want to define another function to simplify it because the code is still similar after the new function is defined). thanks.
Instead of having 5 variables condition_*, use a list, conditions:
conditions=[1]*5 # initialize conditions as you wish
for line in input_file:
for i,condition in enumerate(conditions):
if condition:
conditions[i]=My_Function(A_tuple[i],B_tuple[i])
What about something like
conditions = [condition_A, condition_B, condition_C, condition_D, condition_E]
condition_test = lambda c, i: My_Function(A_tuple[i], B_tuple[i]) if c else c
for line in input_file:
conditions = [condition_test(c, i) for i, c in enumerate(conditions)]
'line' is not referenced in teh loop, is that an error in simplifying it for posting?
How about
condition=1 #or 2 or...
for line in input_file:
My_Function(A_tuple[condition],B_tuple[condition])
Before refactoring your code on a purely syntactic level (which is covered in examples above), it might be useful to evaluate what you're doing with the code on a functional level
Check out your condition_x variables. I think you might be using the same variable for two different things (both type-wise and logically) - usually a bad idea in a weakly typed language. It looks to me as if the user sets a condition to true or false, and then that condition is assigned the output - is the output boolean? is it related to the original value of that variable? Rethinking this might lead to more understandable code.
It is also difficult to evaluate how this can be refactored without seeing what goes in to condition_x - since these might have commonalities.
One more sample(not solution) based on unutbu's:
data = [1,2,3,'',4,5,6, '', 0]
for i in (i for i in xrange(len(data)) if data[i] not in ['',0]):
data[i] += 1
Sorry if duplicate
Here is a generic solution where you can have custom index and you can also access conditions by name if need be and it can be easily extended to add any new complexities
class Condition(object):
def __init__(self, active, index1, index2):
self.active = active
self.index1 = index1
self.index2 = index2
conditions = {
'A': Condition(True,0,0),
'B': Condition(True,1,1),
'C': Condition(True,2,2),
'D': Condition(True,3,3),
'E': Condition(True,4,4),
}
for line in input_file:
for condition in conditions.itervalues():
if condition.active:
condition.active = My_Function(A_tuple[condition.active.index1], B_tuple[condition.active.index2])

Categories