imported module and current file don't work together - python

First and foremost, I'm not a native english speaker (just to make that clear)
I have written a script for my numeric class in which i computed all necessary functions to pass my class. Now I want to implement everything into a GUI to make things easier.
For the whole testing I worked with a 'test' file to see what types the outputs are and so on. The file is called Numerik_Funktionen1 and is imported to every file im working on. Now here is the problem:
This is a class and function i've written:
class LR:
def LR_zerlegung(self, A, b = 0.):
'''
splits Matrix A in L and R
L = lower triangular matrix -> linke untere Dreiecksmatrix
R = upper triangular matrix -> rechte obere Dreiecksmatrix
returns (L, R) as tupel
'''
self.A = np.copy(A) * 1.
self.ALr = A * 1.
self.n = len(self.A[0])
self.b = b
self.L = np.eye(self.n)
for k in range(self.n-1):
for i in range(self.n)[k+1:self.n]:
self.L[i, k] = self.ALr[i, k] / self.ALr[k, k]
self.ALr[i, k] = 0
for j in range(self.n)[k+1:self.n]:
self.ALr[i, j] = self.ALr[i, j] - self.L[i, k] * self.ALr[k, j]
self.R = self.ALr
print('Ax = b')
print('A', '\n', self.A,"\n")
print('b', '\n', self.b,"\n")
print('L', '\n', self.L,"\n")
print('R', '\n', self.R,"\n")
return self.L, self.R
The problem I run into is best described with code (I now it's neither well written nor good looking code, sorry)
import Numerik_Funktionen1
a = input("a eingeben: ")
b = input("b eingeben: ")
array_from_string = [s.split(',') for s in a.split(';')]
array_from_string2 = [s.split(',') for s in b.split(';')]
c = np.asarray(array_from_string)
d = np.asarray(array_from_string2)
A = c.astype(int)
b = d.astype(int)
The input for a looks like this: 2,3;5,4
and for b 2;4
After the proceeding A is an array
(array([[2, 3],
[5, 4]]))
and b as well (array([[2],
[2]]))
The call of the function looks like this: Numerik_Funktionen1.LR.LR_zerlegung(A, b)
So far so good, but if I want to take the previously described function LR_zerlegung, it returns this: 'numpy.ndarray' object has no attribute 'A'
I don't know what I do wrong and why it won't correspond with the Numerik_Funktionen1. I know my question in not well formulated and im sorry for that in advance.
Thank you

Related

How to concatenate over 2 ndarray(variable) in loop (one of these is EMPTY in first loop )

I want to achieve this function in Python like Matlab
in matlab, the code is
A = [];
for ii = 0:9
B = [ii, ii+1, ii**2];
C = [ii+ii**2, ii-5];
A = [A, B, C];
end
but in Python, use np.hstack or np.concatenate, the ndarray must have same number of dimensions
if the A in first loop is empty, the code will make mistake as following:
for ii in range(10):
B = np.array([ii, ii+1, ii**2])
C = np.array([ii+ii**2, ii-5])
if ii == 0:
A = np.hstack([B, C])
else:
A = np.hstack([A, B, C])
and, that is my Python code, B and C are variable, not repeat the ndarray, plz don't close my question!
for ii in range(10):
B = np.array([ii, ii+1, ii**2])
C = np.array([ii+ii**2, ii-5])
if ii == 0:
A = np.hstack([B, C])
else:
A = np.hstack([A, B, C])
but, i think it a little troublesome and unreadable.
how can i rewrite it?(It's better to use only one line of code)
Without knowing what the result Should be - I think this is close
import numpy as np
q = np.arange(10)
bs = np.vstack((q,q+1,q**2)).T
cs = np.vstack((q,q**2,q-5)).T
a = np.hstack((bs,cs))
Or maybe:
a = np.hstack((bs,cs)).ravel()

Two number Sum program in python O(N^2)

I am used to write code in c++ but now I am trying to learn python. I came to know about the Python language and it is very popular among everyone. So I thought, let's give it a shot.
Currently I am preparing for companies interview questions and able to solve most of them in c++. Alongside which, I am trying to write the code for the same in Python. For the things which I am not familiar with, I do a google search or watch tutorials etc.
While I was writing code for my previously solved easy interview questions in python, I encountered a problem.
Code : Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Given an array of integers, print the indices of the two numbers such that they add up to a specific target.
def twoNum(*arr, t):
cur = 0
x = 0
y = 0
for i in range (len(arr) - 1):
for j in range (len(arr) - 1):
if(i == j):
break
cur = arr[i] + arr[j]
if(t == cur):
x = arr[i]
y = arr[j]
break
if(t == cur):
break
print(f"{x} + {y} = {x+y} ")
arr = [3, 5, -4, 8, 11, 1, -1, 6]
target = 10
twoNum(arr, t=target)
So here is the problem: I have defined x, y in function and then used x = arr[i] and y = arr[j] and I m printing those values.
output coming is : is 0 + 0 = 10 (where target is 10)
This is I guess probably because I am using x = 0 and y = 0 initially in the function and it seems x and y values are not updating then I saw outline section in VSCode there I saw x and y are declared twice, once at the starting of the function and second in for loop.
Can anyone explain to me what is going on here?
For reference, here is an image of the code I wrote in C++
Change this:
def twoNum(*arr, t):
to this:
def twoNum(arr, t):
* is used to indicate that there will be a variable number of arguments, see this. It is not for pointers as in C++.
Basically what you are trying to do is to write C code in python.
I would instead try to focus first on how to write python code in a 'pythonic' way first. But for your question - sloving it your way using brute force in python:
In [173]: def two_num(arr, t):
...: for i in arr:
...: for j in arr[i + 1: ]:
...: if i + j == t:
...: print(f"{i} + {j} = {t}")
...: return
Here's a way to implement a brute force approach using a list comprehension:
arr = [1,3,5,7,9]
target = 6
i,j = next((i,j) for i,n in enumerate(arr[:-1]) for j,m in enumerate(arr[i+1:],i+1) if n+m==target)
output:
print(f"arr[{i}] + arr[{j}] = {arr[i]} + {arr[j]} = {target}")
# arr[0] + arr[2] = 1 + 5 = 6
Perhaps even more pythonic would be to use iterators:
from itertools import tee
iArr = enumerate(arr)
i,j = next((i,j) for i,n in iArr for j,m in tee(iArr,1)[0] if n+m==target)
When you get to implementing an O(n) solution, you should look into dictionaries:
d = { target-n:j for j,n in enumerate(arr) }
i,j = next( (i,d[m]) for i,m in enumerate(arr) if m in d and d[m] != i )

Getting an Array/Vector from PARI/GP in Python using Ctypes

I have written a code to compare the solution of sympy and PARI/GP, how ever I am facing a problem to get an array/vector from PARI/GP.
When I try to return the vector res from PARI/GP function nfroots, I get a address like this (see the last line) -
[3, 4]
elements as long (only if of type t_INT):
3
4
<__main__.LP_LP_c_long object at 0x00000000056166C8>
how can I get the res as vector/array from nfroots so I can use that array like normal python vector/array?
The code is given below to download the libpari.dll file, click here-
from ctypes import *
from sympy.solvers import solve
from sympy import Symbol
pari = cdll.LoadLibrary("libpari.dll")
pari.stoi.restype = POINTER(c_long)
pari.cgetg.restype = POINTER(POINTER(c_long))
pari.gtopoly.restype = POINTER(c_long)
pari.nfroots.restype = POINTER(POINTER(c_long))
(t_VEC, t_COL, t_MAT) = (17, 18, 19) # incomplete
pari.pari_init(2 ** 19, 0)
def t_vec(numbers):
l = len(numbers) + 1
p1 = pari.cgetg(c_long(l), c_long(t_VEC))
for i in range(1, l):
#Changed c_long to c_float, but got no output
p1[i] = pari.stoi(c_long(numbers[i - 1]))
return p1
def Quartic_Comparison():
x = Symbol('x')
#a=0;A=0;B=1;C=-7;D=13/12 #PROBLEM 1
a=0;A=0;B=1;C=-7;D=12
#a=0;A=0;B=-1;C=-2;D=1
solution=solve(a*x**4+A*x**3+B*x**2+ C*x + D, x)
print(solution)
V=(A,B,C,D)
P = pari.gtopoly(t_vec(V), c_long(-1))
res = pari.nfroots(None, P)
print("elements as long (only if of type t_INT): ")
for i in range(1, pari.glength(res) + 1):
print(pari.itos(res[i]))
return res #PROBLEM 2
f=Quartic_Comparison()
print(f)
res is an element from the PARI/C world. It is a PARI vector of PARI integers (t_VEC of t_INTs). Python does not know it.
If it is to be processed further on the Python side, it must be converted. This is generally necessary if data needs to be exchanged between Python and the PARI/C world.
So if you have a t_VEC with t_INTs on the PARI/C side, as in this case, you most likely want to convert it to a Python list.
One possible approach might look like this:
...
roots = pari.nfroots(None, P)
result = []
for i in range(1, pari.glength(roots) + 1):
result.append(pari.itos(roots[i]))
return result

I am passing a set of N values to a loop but cant get it to print an ouput

I cannot seem to get an output when I pass numbers to the function. I need to get the computed value and subtract it from the exact. Is there something I am not getting right?
def f1(x):
f1 = np.exp(x)
return f1;
def trapezoid(f,a,b,n):
'''Computes the integral of functions using the trapezoid rule
f = function of x
a = upper limit of the function
b = lower limit of the function
N = number of divisions'''
h = (b-a)/N
xi = np.linspace(a,b,N+1)
fi = f(xi)
s = 0.0
for i in range(1,N):
s = s + fi[i]
s = np.array((h/2)*(fi[0] + fi[N]) + h*s)
print(s)
return s
exactValue = np.full((20),math.exp(1)-1)
a = 0.0;b = 1.0 # integration interval [a,b]
computed = np.empty(20)
E=np.zeros(20)
exact=np.zeros(20)
N=20
def convergence_tests(f, a, b, N):
n = np.zeros(N, 1);
E = np.zeros(N, 1);
Exact = math.exp(1)-1
for i in range(N):
n[i] = 2^i
computed[i] = trapezoid(f, a, b, n[i])
E = abs(Exact - computed)
print(E, computed)
return E, computed
You have defined several functions, but your main program never calls any of them. In fact, your "parent" function convergence_test cannot be called, because it's defined at the bottom of the program.
I suggest that you use incremental programming: write a few lines; test those before you proceed to the next mini-task in your code. In the posting, you've written about 30 lines of active code, without realizing that virtually none of it actually executes. There may well be several other errors in this; you'll likely have a difficult time fixing all of them to get the expected output.
Start small and grow incrementally.

Python extracting/editing all constants involved in a function via AST?

Let's say I have the following code:
def f(x, y, n = 1):
k = 10
z = x**n + y**n + k
return z
def g(x):
alpha = 10
return f(x, alpha)
I would like to analyze g to extract from it all constants involved in returning its output: alpha, n, and k. Is it possible to do this in python, perhaps by using the ast library?
Further, if the above is possible, is it then possible to edit some of those constants:
h = create_new_function(g, g.alpha = 25, f.k = 50)
It would be quite something if this were possible!
You can use the ast and
inspect modules to do this task
Use inspect.getsource to get the source of the function where you want to extract the variables.
Parse the function source code to an ast node using ast.compile
Go through the child nodes inside the body of the root node and find instances of the class ast.Assign.
For each assignation, fetch the left & right operands using the attributes targets and value of such nodes
You can do something like this (I assume all values in the assignations are numbers):
import ast
from inspect import getsource
from operator import attrgetter
# This is the function we want to know its variables
def foo():
a, b, c = 1, 2, 3
d = 0
# Get the code and parse it to an ast node
code = getsource(foo)
root = ast.parse(code)
# Get all assignations
assigns = root.body[0].body
for assign in assigns:
# For each assignation...
# Find left operands on the assignation
vars = []
for target in assign.targets:
if isinstance(target, ast.Tuple):
vars.extend(target.elts)
else:
vars.append(target)
# Get operand names
varnames = list(map(attrgetter('id'), vars))
# Also get right operands (we assume are all numbers)
if isinstance(assign.value, ast.Tuple):
values = list(map(attrgetter('n'), assign.value.elts))
else:
values = (assign.value.n,)
# Print info
print(', '.join(varnames) + ' = ' + ', '.join(map(str, values)))
The output of the code above is:
a, b, c = 1, 2, 3
d = 0

Categories

Resources