Python prints arrays twice - python

I have written the following implementation of the Extended Euclidean Algorithm:
def extended_euclid(a, b):
x_k = 1 # read x_k
x_k1 = 0 # read x_(k+1)
y_k = 0 # read y_k
y_k1 = 1 # read y_(k+1)
sign = 1
while b != 0:
q = a//b
r = a - q*b
a = b
b = r
xx = x_k1
yy = y_k1
x_k1 = q*x_k1 + x_k
y_k1 = q*y_k1 + y_k
x_k = xx
y_k = yy
sign = -sign
x = sign*x_k
y = sign*y_k
return [a, x, y]
It works as exptected but when I try to print out the result of a function call using the standard function "print" the output gets printed twice. So when I do
print(extended_euclid(15,10))
I get the output
[5, 1, 1]
[5, 1, 1]
I do not understand why the output gets printed twice, could you explain that to me.
Also when I do
a = extended_euclid(15,10)
print(a[1])
I get
1
1
which I do not understand either.
EDIT: The problem was that I mistakenly imported a file twice, which led to some unexpected results. Maybe this helps somebody.

Check the rest of your code, if you print this euclid function somewhere, delete that print and just call function instead. On my machine this code prints only one result.

Related

Calling a function that imports its result from another function in Python

I have a code in Python f1 that creates two functions, the second function gets the result from the first one:
a = 3
b = 4
def fS(a,b):
x = a+b
return x
y = fS(a,b)
print(y)
def fM(a,b,y):
z = a*b*y
return z
w = fM(a,b,y)
print(w)
And another code f2 that uses these functions, both imported from the first code:
from f1 import *
a = 6
b = 4
c = a+1
d = b+1
p = fS(c,d)
print(p)
q = fM(c,d,p)
print(q)
Function fS gives the sum of two numbers. Function fM gives the product multiplied by the previous result of the sum. In f2, both numbers should be added by 1 before the first function. Running f1, it gives the correct result for y and w:
7
84
But running f2, it gives the result from f1 and results from f2:
7
84
12
420
The results are correct but my intention is to print only the results from f2 (p = 12 and q = 420) when running it and not those first two results (7 and 84):
12
420
I tried to solve it by inserting the statement if __name__ == '__main__': in f1 before setting the values of a and b, but got an error message: name 'a' is not defined in y = fS(a,b) because these values cannot be read by running f2. What am I missing here? Is there a way I could do it without creating a new file?
Try wrapping whole code outside defs in f1 in that if. After changing f1 to this code, it should work.
def fS(a,b):
x=a+b
return x
def fM(a, b ,y):
z=a*b*y
return z
if __name__ == '__main__':
a = 3
b = 4
y = fS(a,b)
print(y)
w = fM(a, b, y)
print (w)
One solution would be to simply delete the print functions from f1.
If you still want to be able to print those values but only when you want, simply create functions in f1 like this:
def printFirstFunction(a, b):
print(fS(a,b))
def printSecondFunction(a, b, y):
print(fM(a,b,y))
and call these functions only when you need to print those values.
To solve the problem where you wrote the main function, you should provide that code too. Most likely you forgot to intialize those variables or you defined the function before declaring them, but we can't tell if you don't show us that code.

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

Why are lists created by a function not iterable

I'm new to python and don't understand much. I created a function that takes a number and puts all the integers which lead up to that number, including that number, into a list. Or so I thought, turns out I cant actually use the created list as a list. Any ideas on how I can make it useable?
def break_up(x):
"""breaks up the the integers adding up to a number x, starting at 1. Works for any positive number or 0"""
y = 1
b = 1
a = []
while y <= x:
n = x - x + b
b = b + 1
y = y + 1
a.append(n)
print(a)
As people have commented, your indentation is incorrect, but in addition you are not actually calling the function.
The function needs to return an object. An object created in a function stays there and is not visible outside (unless it is global) - this is called encapsulation and is an important programming technique which enables functions to be used anywhere.
Note that even the multi-line comment has to be indented (and I have made it multi-line)
Here is my version of your program:
def break_up(x):
"""
breaks up the the integers adding up to a number x, starting at 1.
Works for any positive number or 0
"""
y = 1
b = 1
a = []
while y <= x:
n = x - x + b
b = b + 1
y = y + 1
a.append(n)
return a # <<<< added
# At this point, the name 'a' is not visible
thing = break_up(5)
print(thing)
# or
print(break_up(5))
Just for fun, try this:
$ python3 -i gash.py
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
>>> help(break_up)

Python and matlab gives different answers

I need to get 3 values from 3 equations as part of an error correcting method for S-parameters. The equations are shown below.
The matlab code went as follows.
syms a b c
eqn1 = (G_A1*a)+(b)-(G_A1*G_M1*c) == G_M1; %short
eqn2 = (G_A2*a)+(b)-(G_A2*G_M2*c) == G_M2; %load
eqn3 = (G_A3*a)+(b)-(G_A3*G_M3*c) == G_M3; %open
%[A,B] = equationsToMatrix([eq1, eq2, eq3], [a, b, c]);
%res = linsolve(A,B);
sol = solve([eqn1, eqn2, eqn3], [a, b, c]);
aSol = sol.a;
bSol = sol.b;
cSol = sol.c;
Giving me the results:
4.9284 - 2.8505i
-11.1951 -37.7373i
-31.2705 -64.5481i
The code used in Python was
a = np.array([[G_A1,G_A2,G_A3], [1,1,1], [(-G_A1*G_M1),(-G_A2*G_M2),(-G_A3*G_M3)]])
b = np.array([G_M1,G_M2,G_M3])
x = np.linalg.solve(a, b)
Giving
-0.24421332 -0.021397452j
-10.1681071 -37.679968ej
-0.77652264 -0.0377357202j
It the code used in Python incorrect?
You need to switch columns and rows in your a-matrix. Try the following change to your python code and you should get the same results as in matlab.
a = np.array([[G_A1,G_A2,G_A3], [1,1,1], [(-G_A1*G_M1),(-G_A2*G_M2),(-G_A3*G_M3)]])
a = a.transpose()
b = np.array([G_M1,G_M2,G_M3])
x = np.linalg.solve(a, b)
To understand this, consider your example, and take the first row of a*x.
This would result in
G_A1*x1+G_A2*x2+G_A3*x3 = G_M1
Looking at your picture, what you want is a.transpose()*x.

Lambda function doesn't return float

I've written the following code for computing the in-center of a triangle. This code is supposed to be for code-golf. Any help would be appreciated.
d = lambda x,y: ((x[0]-y[0])**2+(x[1]-y[1])**2)**0.5
e = lambda w,x,y,z: float(d(y,z)*x[w]+d(z,x)*y[w]+d(x,y)*z[w])/(d(x,y)+d(y,z)+d(z,x))
a,b,c=eval(input())
px,py=e(0,a,b,c),e(1,a,b,c)
print('[%f,%f]' % (px,py))
Input:
([1,2],[2,2],[1,2])
Expected Output:
[1.2928932188134525, 1.7071067811865475]
Actual Output:
[1.000000,2.000000]
Python is doing the maths correctly. Either your logic is wrong or your input is wrong or your expected output is wrong. Given your input, the only possible output for d is 0 or 1 (the Cartesian distance between two points). Doing this, we can simply e to see what it might output for the first function call.
Given:
w = 0
x = [1, 2]
y = [2, 2]
z = [1, 2]
result = float(d(y,z)*x[w]+d(z,x)*y[w]+d(x,y)*z[w])/(d(x,y)+d(y,z)+d(z,x))
becomes:
result = float(d([2, 2],[1, 2])*[1, 2][0]+d([1, 2],[1, 2])*[2, 2][0]+d([1, 2],[2, 2])*[1, 2][0])/(d([1, 2],[2, 2])+d([2, 2],[1, 2])+d([1, 2],[1, 2]))
becomes:
result = float((1.*1 + 0.*2 + 1.*1) / (1. + 1. + 0))
becomes:
result = float(2. / 2.)
result = float(1.)
result = 1. # not 1.2928932188134525
After that, it's up to you to figure out what's wrong as you haven't specified why the expected output is the expected output.
Are you sure that [1.000000,2.000000] isn't a correct answer? This code:
d = lambda x,y: round(((x[0]-y[0])**2.0+(x[1]-y[1])**2.0)**0.5, 12)
e = lambda w,x,y,z: float(round((d(y,z)*x[w]+d(z,x)*y[w]+d(x,y)*z[w])/(d(x,y)+d(y,z)+d(z,x)),12))
a,b,c= input()
px,py=e(0,a,b,c),e(1,a,b,c)
print px, py
return floating numbers, for example:
in: ([1.25325,2.34346], [2.25325,4.34346], [22.25325,22.34346])
out: 2.559632791 4.11015248488

Categories

Resources