Python 3.6: NameError: name 'A' is not defined - python-3.x

I'm very new to Python (3.6). My console is giving me the following error: "NameError: name 'A' is not defined". How can I fix this error?
def NuclearBindingEnergy(A,Z):
a_V=15.67
a_S=17.23
a_C=0.75
a_A=93.2
a_P=0
if A%2==1:
a_P=0
else:
if Z%2==0:
a_P=12.0
else:
a_P=-12.0
B = (a_V)*A - ((a_S)*(A**(2/3))) - (a_C)*(Z**2/(A**(1/3))) - ((a_A)*(((A-(2*Z))**2)/A)) + ((a_P)/A**(1/2))
return B
def NuclearBindingEnergyPerNucleon(A,Z):
return NuclearBindingEnergy(A,Z)/A
print(NuclearBindingEnergy(A,Z))
print(NuclearBindingEnergy(A,Z)/A)

you have to declare A and Z variables values for example as following
A =12
Z = 5
print(NuclearBindingEnergy(A,Z))
print(NuclearBindingEnergy(A,Z)/A)
it will output
55.008666416854204
4.584055534737851

When you use parameters in a function you dont need to define them because they must be defined when the function used, but when you use some function and you want to take some values inside them as a parameter so you must defined them before using in the functions parameter so in your example you just can define A and Z like :-
...
A = 20
Z = 30
print(NuclearBindingEnergy(A,Z))
print(NuclearBindingEnergy(A,Z)/A)
...
And also you can use numbers instead them like:-
...
print(NuclearBindingEnergy(70, 60))
print(NuclearBindingEnergy(80,90)/100)
...

Related

python function with modular variable

hie,
I'm writing my first big python program (3.8) and I try to use a function for several uses (same work but with different targets from existing attributes)
I hope it's clear enough.
here the wanted Job :
it's inside a QT5 GUI (QApplication)
class GuiSuperQuizz(QWidget, QApplication):
...
...
def ajout_pts_blindtest(self, nbr):
x = nbr
x = str(x)
eval("team" + x).ajou_pts(int(self.point_blindtest))
eval("self.score_equip_" + x).setText(str(eval("team" + x).point)) # bug is here
eval("self.gest_score_equip_" + x).setText(str(eval("team" + x).point))
print(eval("team" + x).point)
self.continu[0] = False
self.en_pause[0] = False
self.records_scores()
The interpreter do not recognize the attribute "score_equip_1" and give me an error
AttributeError: 'GuiSuperQuizz' object has no attribute 'score_equip_1'
Yet, I know that attribute works well with this other function that work fine
def ajout_pts_rap_team1(self):
team1.ajou_pts(int(self.point_rap))
self.score_equip_1.setText(str(team1.point))
self.gest_score_equip_1.setText(str(team1.point))
print(team1.point)
self.continu[0] = False
self.en_pause[0] = False
self.aff_ligne4()
self.records_scores()
For not writing 4 functions to target 4 variables that are just incremented (it's a Quizz game with 4 players) I try try to concatenate in 1 function that arrange targets.
if I test the same logic on a very simple lines that works:
test1 = 456
def test(nbr):
x = nbr
x=str(x)
print(eval("test"+x))
test(1)
456
If anyone got some explanations ....

Python: How to define a map of pointers to method inside a class, outside a method

I want to use some method of a class, especified by a parameter. So I have defined a map of pointers with a diccionary. The problem is that Python doesn't let me define it outside another method (for example the constructor). So I wonder if it is posible. Let me show you an example:
class clase():
mapa = { 1 : metodo1,
2 : metodo2 }
def metodo(self,x):
self.mapa[x]()
def metodo1(self):
print("Metodo 1 ejecutado")
def metodo2(self):
print("Metodo 2 ejecutado")
objeto = clase()
objeto.metodo(2)
objeto.metodo(1)
Here the error says that "name 'metodo1' is not defined"; and If I use this other declaration:
class clase():
mapa = { 1 : self.metodo1,
2 : self.metodo2 }
...
The error is "name 'self' is not defined" (and that surprised me so much!)
How I said, I could do it defining the map inside the constructor. It works. But I want to know if there is any way to do it outside any method because I think I would be more readable during the maintainnig of the code.
ACTUALIZATION:
I proved declaring the map at the end:
class clase():
def metodo(self,x):
self.mapa[x]()
def metodo1(self):
print("Metodo 1 ejecutado")
def metodo2(self):
print("Metodo 2 ejecutado")
mapa = { 1 : metodo1,
2 : metodo2 }
objeto = clase()
objeto.metodo(2)
But I got another error: "metodo2() missing 1 required positional argument: 'self'"

md5(str.encode(var1)).hexdigest() giving hex value as 382fbe213f159eecf85facb256f265d0 - how to know the var1?

While running the test case, my code is failing as the expected value in hex is different then my answer.
for example, my ws_std value is 13.06 i.e. var1
md5(str.encode(var1)).hexdigest() giving hex value as 382fbe213f159eecf85facb256f265d0
But I am not sure if it matches with the hex value.
Getting error in below code :-
variables = ["ws_std", "p_range", "corr", "dew_month", "max_gust_month", "max_gust_value", "avg_temp", "temp_range", "max_p_range_day", "num_days_std", "median_b_days"]
answers = [ws_std, p_range, corr, dew_month, max_gust_month, max_gust_value, avg_temp, temp_range, max_p_range_day, num_days_std, median_b_days]
answer_dict = dict()
for var, ans in zip(variables, answers):
answer_dict[var] = md5(str.encode(ans)).hexdigest()
with open('test_files/hash.pk', 'rb') as file:
hash_dict = pickle.load(file)
def test_ws_std():
assert hash_dict["ws_std"] == answer_dict["ws_std"]
Error Code:-
========================================================== FAILURES ==========================================================
________________________________________________________ test_ws_std _________________________________________________________
def test_ws_std():
> assert hash_dict["ws_std"] == answer_dict["ws_std"]
E AssertionError: assert 'c8cc550afa85...2c6946c238f36' == '382fbe213f159...facb256f265d0'
E - c8cc550afa85496c4ee2c6946c238f36
E + 382fbe213f159eecf85facb256f265d0
test.py:40: AssertionError
see comments below .
output required : ws_std

How to get python to recognize missing value when converting list to dictionary?

Working in Python and I've tried a number of different variations but this is my latest. I'm trying to convert "user" list to a dictionary that looks like this:
{
"Grae Drake": 98110,
"Bethany Kok": None,
"Alex Nussbacher": 94101,
"Darrell Silver": 11201,
}
It would show the user's name and zip code, but one user is missing a zip code so I want it to show 'None' where the zip code is missing. Converting isn't the issue, but I'm trying to make it more dynamic in that it will recognize the missing zip code and input 'None' instead.
users = [["Grae Drake", 98110], ["Bethany Kok"], ["Alex Nussbacher", 94101], ["Darrell Silver", 11201]]
def user_contacts():
for name, z in users:
[None if z is None else z for z in users]
user_dict = dict(users)
return user_dict
One possible solution:
users = [["Grae Drake", 98110], ["Bethany Kok"], ["Alex Nussbacher", 94101], ["Darrell Silver", 11201]]
d = dict((u + [None])[:2] for u in users)
print(d)
Prints:
{'Grae Drake': 98110, 'Bethany Kok': None, 'Alex Nussbacher': 94101, 'Darrell Silver': 11201}

How to Pass tuple lists to a function arguments in python

I have the following code which works ok:
def func1():
return Pipeline([('cont_inf_replacer', replaceInf()),
])
make_column_transformer((func1(), features['cat1']),
(func2(), features['cat2']),
(func3(), features['cat3'])
)
Now, I would like to pass the function argument as a variable
func_dict = {'cat1': func1, 'cat2':func2, 'cat3': func3}
for c in features.keys():
arg_tuple += (func_dict[c], features[c])
make_column_transformer(arg_tuple)
I would expect arg_tuple should expand/unpack into
func1(), features['cat1']),
(func2(), features['cat2']),
(func2(), features['cat3'])
But received the following error. I did a search and could not find the proper solution
ValueError: not enough values to unpack (expected 2, got 1)
This is how make_column_transformer() is defined:
make_column_transformer(*transformers, **kwargs)
Unpack with *arg_tuple seems to work (no error when call make_column_transfer, but the results are different, see below)
make_column_transformer((func1(),features['_cat_'])): output
ColumnTransformer(n_jobs=None, remainder='drop', sparse_threshold=0.3,
transformer_weights=None,
transformers=[('pipeline', Pipeline(memory=None,
steps=[('cont_inf_replacer', <__main__.replaceInf object at 0x7f87d19d6ba8>)]), ['cat1', 'cat2', 'cat3'])])
With *arg_tuple,
make_column_transformer(*arg_tuple)
ColumnTransformer(n_jobs=None, remainder='drop', sparse_threshold=0.3,
transformer_weights=None,
transformers=[('function', <function _pip_cont at 0x7f87d1a006a8>, ['cat1', 'cat2', 'cat3'])])
make_column_transformer(*arg_tuple) will unpack ((),(),()) correctly
You should instead try the following
pipline_step['cat1'] = [('test_pipeline',
Pipeline([SimpleImputer(xxxxxxxx)]))]
list_pipeline = Pipeline()
list_pipeline.steps.append(pipeline)
So in this way, instead of a for loop, you can attach the steps depending on the availability of the subsets (in this example, cat1 is available). And you can pass the subset name as a key as the pipeline steps.
Per #onyambu, *arg_tuple solved the issue
so the following code works
make_column_transfer(*arg_tuple)
This will unpack a "list" of tuples and pass it to the function *transformers
Try with this:
def tupler(txt):
x = eval('tuple(' + str(txt) + ')')
print len(x)
tuple1 = (1,2,3,4,5)
string1 = str(tuple1)
tupler(string1)
Eval function is the trick.
For more details about eval function, click here

Resources