Strange output of a very simple code? - function

I'm very new to python, but I found this strange:
Code: I was typing in Sagemathcloud's sageworksheet file:
x=y+1
def f(x):
return y
x=-1
print(x)
print(f(x))
As an output, I kept getting 7 or sometimes 49, something quite randomnumbers no matter what value of x I input. Any insights please?
P.S. I'm trying to make it look like a code, but I'm, not sure how to do that, for example, def was in the next lmine after I typed: x=y+1.

If that's the only code you have, then y isn't defined before it is used. y will take the value of what was previously in the memory space it's using - and that may not even be an int which causes the randomness of the numbers you're experiencing.

Related

Learning About constructors in Python

I have recently learnt about Exception Handling concepts. I am not able to understand why self.arg=arg doesnt work whereas self.msg=arg works in the below code.
class MyException(Exception):
def init(self,arg):
self.msg=arg
def check(key,value):
print('Name={} Balance={}'.format(key,value))
if(v<2000):
raise MyException('Balance amt is less in the account of ',key)
bank={'Raj':5000,'Vikas':10000,'Nishit':500,'John':321211}
for k,v in bank.items():
try:
check(k,v)
except MyException as obj:
print(obj)
It should work. You're basically assigning the value of the argument arg to the instance variable arg, no conflict there, a classic example that can be found here in Documentation.
Maybe you mistyped, used a symbol from another alphabet, or forgot a spacebar on that line? Without the error message all I can do is guess. So try replacing msg in your working code with arg once again, it may fix the problem.
By the way, it would be easier to use f-strings instead of formatting:
f'Name={key} Balance={value}'
f'Balance amt is less in the account of {key}'
It's shorter, you don't have to worry about messing up the order or number of arguments, and the code is more readable.

Linear function with live data

I am an absolute newbie on the programming thing and really desperate. I picked up a high end task to solve as it seems to me...
I know there are tons of explanations for solving y = mx + b with python but they're all for the situation with "solid" data. I am trying to realize it with live data.
So far, i have two data streams, which I successful directed into two lists - please see code below.
for graph in basis_graph:
high_1 = float(graph.high)
low_1 = float(graph.low)
if high_1 > 0:
graph_high.append([high_1])
if low_1 > 0:
graph_low.append([low_1])
Now comes the tricky part and I DON`T GET IT. I need a function that calculates me "m". Something like that:
def function_signal():
if graph_high[-1] < graph_high[-2]:
please, mr. computer, calculate me "m"
I tried something like
def signal():
if graph_low[-1] < graph_low[-2]:
print("a")
ay1 = graph_low[-1]
by1 = graph_low[-2]
m = ay1 - by1
return m
print(m(ay1, ay2))
Two days I tried EVERYTHING from what I know so far but the only thing I earned was a cascade of Tracebacks. From "I can't divide two list objects" to " "m" is not defined" and so on and so on...
In the case above for example NOTHING happens. Sometimes he says "m is not defined"...
Please, if there's someone out there who is willing to help me than I would really appreciate it.
Thanks in advance.

sympy autowrap (cython): limit of # of arguments, arguments in array form?

I have the following issue:
I want to use autowrap to generate a compiled version of a sympy matrix, with cells containing sympy expressions. Depending on the specification of my problem, the number of arguments can get very large.
I ran into the following 2 issues:
The number of arguments that autowrap accepts seems to be limited to 509.
i.e., this works:
import sympy
from sympy.utilities.autowrap import autowrap
x = sympy.symbols("x:509")
exp = sum(x)
cyt = autowrap(exp, backend="cython", args=x)
and this fails to compile:
x = sympy.symbols("x:510")
exp = sum(x)
cyt = autowrap(exp, backend="cython", args=x)
The message I get seems not very telling:
[...] (Full output upon request)
Generating code
c:\users\[classified]\appdata\local\temp\tmp2zer8vfe_sympy_compile\wrapper_module_17.c(6293) : fatal error C1001: An internal error has occurred in the compiler.
(compiler file 'f:\dd\vctools\compiler\utc\src\p2\hash.c', line 884)
To work around this problem, try simplifying or changing the program near the locations listed above.
Please choose the Technical Support command on the Visual C++
Help menu, or open the Technical Support help file for more information
LINK : fatal error LNK1257: code generation failed
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\\BIN\\x86_amd64\\link.exe' failed with exit status 1257
Is there any way around this? I would like to use versions of my program that need ~1000 input variables.
(I have no understanding of C/cython. Is this an autowrap limitation, a C limitation ...?)
Partly connected to the above:
Can one compile functions that accept the arguments as array.
Is there any way to generate code that accepts a numpy array as input? I specifically mean one array for all the arguments, instead of providing the arguments as list. (Similar to lambdify using a DeferredVector). ufuncify supports array input, but as I understand only for broadcasting/vectorizing the function.
I would hope that an array as argument could circumvent the first problem above, which is most pressing for me. Apart from that, I would prefer array input anyways, both because it seems faster (no need to unpack the numpy array I have as input into a list), and also more straightforward and natural.
Does anyone have any suggestions what I can do?
Also, could anyone tell me whether f2py has similar limitations? This would also be an option for me if feasible, but I don't have it set up to work currently, and would prefer to know whether it helps at all before investing the time.
Thanks!
Edit:
I played around a bit with the different candidates for telling autowrap that the input argument will be something in array form, rather than a list of numbers. I'll document my steps here for posterity, and also to increase chances to get some input:
sympy.DeferredVector
Is what I use with lambdify for the same purpose, so I thought to give it a try. However, warning:
A = sympy.DeferredVector("A")
expression = A[0]+A[1]
cyt = autowrap(expression, backend="cython", args=A)
just completely crashed my OS - last statement started executing, (no feedback), everything got really slow, then no more reactions. (Can only speculate, perhaps it has to do with the fact that A has no shape information, which does not seem to bother lambdify, but might be a problem here. Anyways, seems not the right way to go.)
All sorts of array-type objects filled with the symbols in the expression to be wrapped.
e.g.
x0 ,x1 = sympy.symbols("x:2")
expression = x0 + x1
cyt = autowrap(expression, backend="cython", args=np.array([x0,x1]))
Still wants unpacked arguments. Replacing the last row by
cyt = autowrap(expression, backend="cython", args=[np.array([x0,x1])])
Gives the message
CodeGenArgumentListError: ("Argument list didn't specify: x0, x1 ", [InputArgument(x0), InputArgument(x1)])
Which is a recurrent theme to this approach: also happens when using a sympy matrix, a tuple, and so on inside the arguments list.
sympy.IndexedBase
This is actually used in the autowrap examples; however, in a (to me) inintuitive way, using an equation as the expression to be wrapped. Also, the way it is used there seems not really feasible to me: The expression I want to cythonize is a matrix, but its cells are themselves longish expressions, which I cannot obtain via index operations.
The upside is that I got a minimal example to work:
X = sympy.IndexedBase("X",shape=(1,1))
expression = 2*X[0,0]
cyt = autowrap(expression, backend="cython", args=[X])
actually compiles, and the resulting function correctly evaluates - when passed a 2d-np.array.
So this seems the most promising avenue, even though further extensions to this approach I keep trying fail.
For example this
X = sympy.IndexedBase("X",shape=(1,))
expression = 2*X[0]
cyt = autowrap(expression, backend="cython", args=[X])
gets me
[...]\site-packages\sympy\printing\codeprinter.py", line 258, in _get_expression_indices " rhs indices in %s" % expr)
ValueError: lhs indices must match non-dummy rhs indices in 2*X[0]
even though I don't see how it should be different from the working one above.
Same error message when sticking to two dimensions, but increasing the size of X:
X = sympy.IndexedBase("X",shape=(2,2))
expression = 2*X[0,0]+X[0,1]+X[1,0]+X[1,1]
cyt = autowrap(expression, backend="cython", args=[X])
ValueError: lhs indices must match non-dummy rhs indices in 2*X[0, 0] + X[0, 1] + X[1, 0] + X[1, 1]
I tried snooping around the code for autowrap, but I feel a bit lost there...
So I'm still searching for a solution and happy for any input.
Passing the argument as an array seems to work OK
x = sympy.MatrixSymbol('x', 520, 1)
exp = 0
for i in range(x.shape[0]):
exp += x[i]
cyt = autowrap(exp, backend='cython')
arr = np.random.randn(520, 1)
cyt(arr)
Out[48]: -42.59735861021934
arr.sum()
Out[49]: -42.597358610219345

define theano function with other theano function output

I am new to theano, can anyone help me defining a theano function like this:
Basically, I have a network model looks like this:
y_hat, cost, mu, output_hiddens, cells = nn_f(x, y, in_size, out_size, hidden_size, layer_models, 'MDN', training=False)
here the input x is a tensor:
x = tensor.tensor3('features', dtype=theano.config.floatX)
I want to define two theano functions for later use:
f_x_hidden = theano.function([x], [output_hiddens])
f_hidden_mu = theano.function([output_hiddens], [mu], on_unused_input = 'warn')
the first one is fine. for the second one, the problem is both the input and the output are output of the original function. it gives me error:
theano.gof.fg.MissingInputError: An input of the graph, used to compute Elemwise{identity}(features), was not provided and not given a value.
my understanding is, both of [output_hiddens] and [mu] are related to the input [x], there should be an relation between them. I tried define another theano function from [x] to [mu] like:
f_x_mu = theano.function([x], [mu]),
then
f_hidden_mu = theano.function(f_x_hidden, f_x_mu),
but it still does not work. Does anyone can help me? Thanks.
The simple answer is NO WAY. In here
Because in Theano you first express everything symbolically and afterwards compile this expression to get functions, ...
You can't use the output of theano.function as input/output for another theano.function since they are already a compiled graph/function.
You should pass the symbolic variables, such as x in your example code for f_x_hidden, to build the model.

Python backtracking

I have a basic problem in Python where I have to verify if my backtracking code found some solutions (I have to find all sublists of 1 to n numbers with property |x[i] - x[i-1]| == m). How do I check if there is some solution? I mean the potentially solutions I find, I just print them and not save them into memory. I have to print a proper message if there is no solutions.
As I suggested in comment, you might want to dissociate computing from I/O printing, by creating a generator of your solutions of |x[i] - x[i-1]| == m
Let's assume you defined a generator for yielding your solutions:
def mysolutions(...):
....
# Something with 'yield', or maybe not.
....
Here is a generator decorator that you can use to check if an implemented generator has a value
from itertools import chain
def checkGen(generator, doubt):
"""Decorator used to check that we have data in the generator."""
try:
first = next(generator)
except StopIteration:
raise RuntimeError("I had no value!")
return chain([first], generator)
Using this decorator, you can now define your previous solution with :
#checkGen
def mysolutions(...):
....
Then, you can simply use it as is, for dissociating your I/O:
try:
for solution in mysolutions(...):
print(solution) #Probably needs some formatting
except RuntimeError:
print("I found no value (or there was some error somewhere...)")