How to covert an array of type Float to Any in Julia? - list

I would like to convert an array to a python like list in Julia.
To create an array of type Any one may initialize an empty array with this syntax array = []. However if I want to perform conversion, i.e. lets take an array of type Array(Float64,1) to type Any, what would be the correct approach?
Or If there are any alternate approaches to create a list in Julia?
My approach to create a function which takes an array and convert it to type any:
function list(x)
x = convert(Any, x)
return x
end
x_test = [0.19, 0.03, 0.27]
t1 = typeof(x_test)
println("type of x_test is: $t1")
x_test = list(x_test)
t2 = typeof(x_test)
println("type of x_test is: $t2")
Output:
type of x_test is: Array{Float64,1}
type of x_test is: Array{Float64,1}
Please suggest a method or solution to achieve this conversion task.
Thanks.

You can do:
julia> list(x) = Any[i for i ∈ x]
list (generic function with 1 method)
julia> list([0.19, 0.03, 0.25])
3-element Vector{Any}:
0.19
0.03
0.25
But as Oscar says in his comments, why would you ever want to do that? It's true that Python performance often suffers because of a lack of type information, that doesn't mean Julia becomes "like Python" if you deliberately prevent the compiler from optimizing (it will become a lot slower though in almost all cases!)

The shortest form is Vector{Any}(a) as in code here:
julia> a=[1,2,3]
3-element Vector{Int64}:
1
2
3
julia> Vector{Any}(a)
3-element Vector{Any}:
1
2
3
However, if you want to be able to hold in a copy of a other elements such as Strings you will be much more efficient by strictly telling that:
julia> b = Vector{Union{eltype(a),String}}(a)
3-element Vector{Union{Int64, String}}:
1
2
3
julia> push!(b,"jan")
4-element Vector{Union{Int64, String}}:
1
2
3
"jan"

You were not far, you just need to convert to an array of Any:
julia> convert(Array{Any}, x_test)
3-element Vector{Any}:
0.19
0.03
0.27
But as others have said, it's not a good idea to hide type information in general because it will just slow things down.

Related

How to set product to 0 if its a product over an empty list in Julia?

In my code I use Julia's prod() function to do a product over the elements of a list. However, sometimes that list is empty, in which case I want prod(myList) to just return 0 (or any fixed number like 1). I tried searching online, but the only things I could find were for iterators or stuff like that.
I'm using Julia version 1.5.2.
Would a simple ternary operator work for your case?
isempty(my_list) ? 0 : prod(my_list)
What you want is incorrect/unconventional. The product of the elements of an empty sequence should be 1, because that is the multiplicative identity element.
"Any fixed number" is easy:
reduce(*, ls; init=1)
But this does not work well with zero, since that is an annihilator and sends the whole product to zero:
julia> ls = [1,2,3]
3-element Array{Int64,1}:
1
2
3
julia> reduce(*, ls; init=0)
0
Now, returning 1 and then checking for that works if you only have integers. It doesn't as soon as you have a product over rationals, since then the resulting 1 could also stem from x * (1/x).
julia> zeroprod(x) = isempty(x) ? zero(eltype(x)) : prod(x)
zeroprod (generic function with 1 method)

sympy separate fractions from variables

Using sympy how do I keep fractions separate from variables
Mul(Fraction(3,5), Pow(K, Integer(2)))
2
3⋅K
────
5
to
3 2
─ K
5
I know this simplified version is not too bad, but when i have really big equations, it gets messy
I'm not very familiar with pretty printing or LaTeX printing but I managed to come up with something. Put UnevaluatedExpr in each of the arguments of Mul:
from sympy import *
from fractions import Fraction
K = symbols("K")
expr1 = Mul(UnevaluatedExpr(Fraction(3,5)), UnevaluatedExpr(Pow(K, Integer(2))))
expr2 = Mul(UnevaluatedExpr(pi/5), UnevaluatedExpr(Pow(K, Integer(2))))
expr3 = ((UnevaluatedExpr(S(1)*3123456789/512345679) * UnevaluatedExpr(Pow(K, Integer(2)))))
pprint(expr1)
pprint(expr2)
pprint(expr3)
Produces:
2
3/5⋅K
π 2
─⋅K
5
1041152263 2
──────────⋅K
170781893
I couldn't find a way to make it print a stacked fraction for the slashed fraction 3/5. Longer fractions seem to work though. If you are printing in LaTeX however, the documentation suggests something like latex(expr1, fold_frac_powers=False) to correct this.
Too bad I couldn't find an elegant solution like putting init_printing(div_stack_symbols=False) at the top of the document.
To elaborate on Maelstrom's Answer, you need to do 2 things to make this work like you want:
Create the separate fraction you want as its own expression.
Prevent the numerator or denominator from being modified when the expression is combined with other expressions.
What Maelstrom showed will work, but it's much more complicated than what's actually needed. Here's a much cleaner solution:
from sympy import *
K = symbols("K")
# Step 1: make the fraction
# This seems to be a weird workaround to prevent fractions from being broken
# apart. See the note after this code block.
lh_frac = UnevaluatedExpr(3) / 5
# Step 2: prevent the fraction from being modified
# Creating a new multiplication expression will normally modify the involved
# expressions as sympy sees fit. Setting evaluate to False prevents that.
expr = Mul(lh_frac , Pow(K, 2), evaluate=False)
pprint(expr)
gives:
3 2
-*K
5
Important Note:
Doing lh_frac = UnevaluatedExpr(3) / 5 is not how fractions involving 2 literal numbers should typically be created. Normally, you would do:
lh_frac = Rational(3, 5)
as shown in the sympy docs. However, that gives undesirable output for our use case right now:
2
3*K
----
5
This outcome is surprising to me; setting evaluate to False inside Mul should be sufficient to do what we want. I have an open question about this.

Get a generator to return first n combinations [duplicate]

This question already has answers here:
How to get the n next values of a generator into a list
(5 answers)
Fetch first 10 results from a list in Python
(4 answers)
Closed 9 days ago.
With linq I would
var top5 = array.Take(5);
How to do this with Python?
Slicing a list
top5 = array[:5]
To slice a list, there's a simple syntax: array[start:stop:step]
You can omit any parameter. These are all valid: array[start:], array[:stop], array[::step]
Slicing a generator
import itertools
top5 = itertools.islice(my_list, 5) # grab the first five elements
You can't slice a generator directly in Python. itertools.islice() will wrap an object in a new slicing generator using the syntax itertools.islice(generator, start, stop, step)
Remember, slicing a generator will exhaust it partially. If you want to keep the entire generator intact, perhaps turn it into a tuple or list first, like: result = tuple(generator)
import itertools
top5 = itertools.islice(array, 5)
#Shaikovsky's answer is excellent, but I wanted to clarify a couple of points.
[next(generator) for _ in range(n)]
This is the most simple approach, but throws StopIteration if the generator is prematurely exhausted.
On the other hand, the following approaches return up to n items which is preferable in many circumstances:
List:
[x for _, x in zip(range(n), records)]
Generator:
(x for _, x in zip(range(n), records))
In my taste, it's also very concise to combine zip() with xrange(n) (or range(n) in Python3), which works nice on generators as well and seems to be more flexible for changes in general.
# Option #1: taking the first n elements as a list
[x for _, x in zip(xrange(n), generator)]
# Option #2, using 'next()' and taking care for 'StopIteration'
[next(generator) for _ in xrange(n)]
# Option #3: taking the first n elements as a new generator
(x for _, x in zip(xrange(n), generator))
# Option #4: yielding them by simply preparing a function
# (but take care for 'StopIteration')
def top_n(n, generator):
for _ in xrange(n):
yield next(generator)
The answer for how to do this can be found here
>>> generator = (i for i in xrange(10))
>>> list(next(generator) for _ in range(4))
[0, 1, 2, 3]
>>> list(next(generator) for _ in range(4))
[4, 5, 6, 7]
>>> list(next(generator) for _ in range(4))
[8, 9]
Notice that the last call asks for the next 4 when only 2 are remaining. The use of the list() instead of [] is what gets the comprehension to terminate on the StopIteration exception that is thrown by next().
Do you mean the first N items, or the N largest items?
If you want the first:
top5 = sequence[:5]
This also works for the largest N items, assuming that your sequence is sorted in descending order. (Your LINQ example seems to assume this as well.)
If you want the largest, and it isn't sorted, the most obvious solution is to sort it first:
l = list(sequence)
l.sort(reverse=True)
top5 = l[:5]
For a more performant solution, use a min-heap (thanks Thijs):
import heapq
top5 = heapq.nlargest(5, sequence)
With itertools you will obtain another generator object so in most of the cases you will need another step the take the first n elements. There are at least two simpler solutions (a little bit less efficient in terms of performance but very handy) to get the elements ready to use from a generator:
Using list comprehension:
first_n_elements = [generator.next() for i in range(n)]
Otherwise:
first_n_elements = list(generator)[:n]
Where n is the number of elements you want to take (e.g. n=5 for the first five elements).
This should work
top5 = array[:5]

How do I tell sympy that ∂b[a]/∂b==1? Derivative on IndexedBase

I have an expression which includes an IndexedBase. I'm taking a partial derivative, but in the output, this is retained:
In [105]: sympy.IndexedBase(b)[a].diff(b)
Out[105]:
∂
──(b[a])
∂b
My b[a] is simply an array b_0, b_1, ..., b_n. Those are all constants, so ∂b[a]/∂b is equal to 1. How do I rephrase my problem such that it evaluates to one?
First of all, install the latest master branch of SymPy (the latest SymPy version doesn't support these features). Otherwise wait for the next SymPy version release.
Anyway, you can get a Kronecker delta function:
In [27]: b = IndexedBase("b")
In [28]: b[a].diff(b[c])
Out[28]:
δ
a,c
If you derive the indexed object by the same index:
In [29]: b[a].diff(b[a])
Out[29]: 1
The operation b[a].diff(b) isn't clearly defined though, and will raise an error.
I would personally interpret b[a].diff(b) as an array of derivatives ∂b[a]/∂b[0], ∂b[a]/∂b[1], ...

method to circumvent if-else checking

I am just wondering if I want to implement a program that converts wavelength to (r,g,b) using the algorithm in this paper (p5-6): http://www.scientificbulletin.upb.ro/rev_docs_arhiva/full49129.pdf, instead of checking the value of wavelength using if-else like
if wavelength>380 and wavelength<410:
# do something
elif wavelength<440:
# do something
elif wavelength<490:
# do something, and so on
Are there some genius method to avoid using if-else statement so that I can speed up the code? More specifically, suppose I store the wavelengths in a list or a numpy array, is it possible to have some sort of 'vectorized' method to generate the (r,g,b) values?
Yes, there are. If you have your wavelengths in a numpy array you can use boolean masks instead of the if ... elif ... clauses.
For your second question about the vectorized operation ... I think you want something like this:
wavelengths = np.array([1,2,3])
conversion = np.array([-0.41,0,0.6]).reshape(3,1) # R, G, B Parts
wavelengths * conversion
# Reshape is needed to get a 3x3 result
array([[-0.41, -0.82, -1.23],
[ 0. , 0. , 0. ],
[ 0.6 , 1.2 , 1.8 ]])
The given formulas are a bit more complicated than this example but StackOverflow isn't about writing you the code. I think with the example you should be able to implement these formulas.