Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert this line of code from Python to Julia?

In brief, I have the code below in Python

[n, m] = f()

and I want to convert it to Julia, which will not be more than one line (I hope).

Here is an example in Python:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from numpy import *

x = [0,1,2]
y = [3,4,5]
x = array(x)
y = array(y)

def f():
    z = concatenate((x, y))
    a = z*2
    b = z*3
    return [a, b]

def g():
    [n,m] = f()
    n = n/2
    m = m/3
    return [n, m]

print(g())

This is how I wanted it to be in Julia, but did not work:

x = [0,1,2]
y = [3,4,5]

function f()
    z = vcat(x, y)
    a = z*2
    b = z*3
    return [a, b]
end

function g()
    [n, m] = f()
    n = n/2
    m = m/3
    return [n, m]
end

print(g())

Here is how I made it work, but I do not want codes like this:

x = [0,1,2]
y = [3,4,5]

function f()
    z = vcat(x, y)
    a = z*2
    b = z*3
    global c = [a, b]
    return c
end

function g()
    n = c[1]
    m = c[2]
    n = n/2
    m = m/3
    return [n, m]
end

f()
print(g())

Thank you very much.

>Solution :

Just drop square brackets like this:

x = [0,1,2]
y = [3,4,5]

function f()
    z = vcat(x, y)
    a = z*2
    b = z*3
    return a, b # here it is not needed, but typically in such cases it is dropped to return a tuple
end

function g()
    n, m = f() # here it is needed
    n = n/2
    m = m/3
    return n, m # here it is not needed, but typically in such cases it is dropped to return a tuple
end

print(g())

The reason why it is typically better to return a Tuple rather than a vector is that Tuple does not perform auto promotion of values (+ it is non-allocating):

julia> (1, 2.0) # here 1 stays an integer
(1, 2.0)

julia> [1, 2.0] # here 1 got implicitly converted to 1.0
2-element Vector{Float64}:
 1.0
 2.0

Of course if you want such implicit behavior use a vector.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading