This question already has answers here:
Python NameError: name is not defined
(4 answers)
Closed 1 year ago.
def sum(a, b, c, d):
result = 0
result = result+a+b+c+d
return result
def length():
return 4
def mean(a, b, c, d):
return float(sum(a, b, c, d))/length()
print(sum(a, b, c, d), length(), mean(a, b, c, d))
I am getting the error message name 'a' is not defined
If you don’t define the variable you’ll gonna get these name errors. Let’s say for example you switch the values when you call these functions -
print(sum(a, b, c, d), length(), mean(a, b, c, d))
Here, in this case you’ll gonna get name b is not defined because Python interpreter doesn’t know what’s the value that variable b is storing.
You need to tell the interpreter what are the values for these variables.
For example - a=10, b=2,.. and so on
a variable is undefined means that you need to define (assign a value) to that variable. For example, a=1 should work.
Related
I have saved my data in julia using the command below
JLD2.#save "myfile.jld2" a, b, c
and I understand I should have used
JLD2.#save "myfile.jld2" a b c.
Is there still any way to access the data in myfile.jld2 file. Right now, if I run
JLD2.#load "myfile.jld2"
I get
1-element Array{Symbol,1}:
Symbol("(a, b, c)")
and not a, b, c data.
Sure you can - just use "a, b, c" as the data identifier.
Setup:
using JLD2
a,b,c = 255,"some nice text",6666.0
JLD2.#save "file.jld2" a, b, c
Identifying and reading the data:
julia> f=jldopen("file.jld2","r")
JLDFile C:\Users\pszufe\file.jld2 (read-only)
└─� (a, b, c)
julia> keys(f)
1-element Array{String,1}:
"(a, b, c)"
julia> read(f,keys(f)[1])
(255, "some nice text", 6666.0)
I'm currently studying pythons, subproccess() with map() in order to integrate it to my program.
Let's say I have a loop like this,
for a, b in itertools.combinations(exchanges, 2):
if (a != None and b != None):
symbols = a.symbols
symbols1 = b.symbols
if symbols is not None and symbols1 is not None:
symbols = [x for x in symbols if x is not None]
symbols1 = [x for x in symbols1 if x is not None]
if symbol != None and symbol in symbols and symbol in symbols1:
execute_function(a, b, symbol, expent,amount)
obviously I want my symbols and symbol1 lists mapped to the function and get it one by one.
and try different combination with it using itertools.
Tried this so far(just for mapping, as I have no knowledge on how to do that itertools comparing in this case), but seems to be returning a nonetype error. Object not callable.
pool = Pool()
pool.map(execute_func(a, b, symbol, expent,amount), symbols)
Any help is appreciated. Thanks.
In what you tried, the error is that the first argument of pool.map() should be a function but you are passing the result of the function, since you are calling it with a, b, symbol, expent, amount.
From what I understand, you want to call the function execute_func for all non-None symbols pair of all two-by-two combinations of the elements of exchanges. Then, I suggest you write the loops and non-None testing as a generator and then pass it to pool.map. Here's a sketch of my solution:
def gen_all_symbol_pairs(sequence):
for a, b in itertools.combinations(sequence, 2):
if a is not None and b is not None:
if a.symbols is not None and b.symbols is not None:
for symbol in a.symbols:
if symbol is not None and symbol in b.symbols:
yield a, b, symbol
with Pool() as pool:
pool.starmap(lambda a, b, symb: execute_func(a, b, symb, expent, amount), gen_all_symbol_pairs(exchanges))
Here, gen_all_symbol_pairs is an iterable that generates all non-None symbol pairs. Also, I used a lambda function to * partially* fill the execute_func function. Finally, I used pool.starmap so that every sequence yielded by the generator is star expanded in three arguments.
Hope this helps!
I'm trying to write a function to back solve for a variable from another function in python, kind of like what Excel solver does.
To simplify my example, I have a function takes in several variables then calculate a price. I will be passing actual values (a,b,c,d,x) into this function so it returns a numeric value.
def calc_price(a,b,c,d,x):
value = a+b*c-d + x
return value
Now I'm given a target price, and a,b,c,d. Only unknown is variable x, so I want to back solve variable x. I want to build this into a function that takes into the same variables as calc_price, with an additional variable target_price.
def solve(target_price, a,b,c,d):
#this function takes in values for target_price, a,b,c,d
#and should do something like this:
target_price = calc_price(a,b,c,d,x)
solve for x <---------this is the part I'm not sure how to do
return x
I created a function like this below to back solve the value x by a loop but it's inefficient in calculating large datasets, so I'm looking for a more efficient solution.
def solve(target_price,a,b,c,d):
x = 0.01
while x < 1:
if abs(target_price - calc_price(a,b,c,d,x)) < 0.001:
return x
x += 0.001
Thank you!
Consider this a demo (as your task is still a bit unclear to me) and make sure to read scipy's docs to learn about the basic guarantees these method provides.
One could argue, that an approach based on root-finding is more appropriate (we are minimizing a function here; therefore the abs-construction in the residual-function), but this approach here does not need you to give some bracketing-interval.
Code:
import numpy as np
from scipy.optimize import minimize_scalar
np.random.seed(0)
""" Utils """
def calc_price(x, a, b, c, d):
value = a+b*c-d + x
return value
def calc_price_res(x, target, a, b, c, d):
value = a+b*c-d + x
return abs(value - target) # we are looking for f(x) == 0
""" Create fake-data (typically the job of OP!) """
a, b, c, d, x = np.random.random(size=5)
fake_target = calc_price(x, a, b, c, d)
print('a, b, c, d: ', a, b, c, d)
print('real x: ', x)
print('target: ', fake_target)
print('noisy obj (just to be sure): ', calc_price_res(x, fake_target, a, b, c, d))
""" Solve """
res = minimize_scalar(calc_price_res, args=(fake_target, a, b, c, d))
print('optimized x: ', res.x)
print('optimized fun: ', res.fun)
Output:
a, b, c, d: 0.548813503927 0.715189366372 0.602763376072 0.544883182997
real x: 0.423654799339
target: 0.858675077275
noisy obj (just to be sure): 0.0
optimized x: 0.423654796297
optimized fun: 3.04165614917e-09
How can I import a variable from another script using python 3?
Example:
I have two scripts that we shall call script_1.py and script_2.py.
script_1.py:
class Calculate():
def addition():
a = 5
b = 2
c = a + b
Q: How can I use this second script (script_2.py) to print the variable c from the script_1.py?
You cannot do this since c is not a global variable and doesn't even seem to exist outside of addition. Even if it does exist outside of your class, then the addition method (which should either be def addition(self) or be declared with #staticmethod decorator by the way) won't change it since it's not declared as a global variable in it.
Script 1
class Calculate():
#staticmethod
def addition():
a = 5
b = 2
c = a + b
return c
Script 2
from script_1 import Calculate
print(Calculate().addition())
Will output the value of c (eg 7).
If you need a global variable (you almost certainly don't) :
Script 1
c = None
class Calculate():
#staticmethod
def addition():
global c
a = 5
b = 2
c = a + b
Script 2
from script_1 import c, Calculate
Calculate().addition()
print(c)
You really shouldn't do this. Global variables can lead to serious problems. Global constants however are usually ok.
I'm writing this code for something called 'Project Euler' which is basically a maths/computer science thing online, the link of which can be found here:
So anyway, when I run my code which is in Python 3.5, it doesn't do anything in the shell except the cursor bit blinks.
Here is the code in question:
`mylist=[]
a=1
b=2
c=a+b
def fib():
a=1
b=2
c=a+b
a=b
b=c
c=a+b
if a%2==0:
mylist.append(a) and print(a)
elif b%2==0:
mylist.append(b) and print(b)
elif c%2==0:
mylist.append(c) and print(c)
else:
print(end='')
while a and b and c<4000000:
fib()
print(sum(mylist))'
The question I'm trying to answer is
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
The code is meant to add even Fibonacci numbers up to 4 million to a list and then print the sum of them which would perfectly answer the question but it doesn't seem to work.
You have created an infinite loop here:
while a and b and c < 4000000:
This translates to "while a is truthy and b is truthy and c is less than 4000000", and this will always be True so your while loop will never terminate. What I mean by "truthy" is: does bool(value) return True? If so, then value is "truthy". So 1, 'hello', [], etc., are truthy, and 0, False, [], etc., are not (they are "falsey"). I will not comment on all of your logic because you will benefit more from solving the problem on your own. However, here are a few tips that should get you unstuck:
if you want to check that a, b, and c are all less than 4000000, than you can do this:
while a < 4000000 and b < 4000000 and c < 4000000:
or more succinctly:
while all(i < 4000000 for i in [a, b, c]):
In order to not create an infinite loop, you will need to make sure that either a, b, or c will be greater than 4000000 at some point in your program by incriminating their values. The math you do on a, b, and c inside your fib() function only manipulates three variables called a, b, and c that are local to that function; it does not change the values of the a, b, and c outside of that function.