This is an example array i stored in a string property:
[12, 15, 75, 60]
When i tried to retrieve it
and access the index number, it included every character that denotes the array, for example if i ask for array[0], it gives me '[', instead of '12', array[3] gives me ',' array[6] gives me '5' and so on.
How can blender Python read the string like it does with array?
I tried enclosing things in int(), it throws a message "string indices must be integers" or "invalid literal for int() with base 10
Thank for your advance response!
I didn't include any code snippet as this problem is simple enough to understand, thanks, more power
If you want a string array let's convert it this way.
a = '[12, 15, 75, 60]'
b = a[1:len(a)-1].split(",")
print(b[0])
If you want a int array let's convert it this way.
a = '[12, 15, 75, 60]'
b = list(map(int, a[1:len(a)-1].split(",")))
print(b[0])
Related
So i am having an Array in Lua, lets say:
local Array = {1, 8, 10, 15, 20, 30}
so now i want to know if a specific number is in the Array. So if did this:
local number = 4
if Array[number] then
print("Is in Array")
else
print("Not in Array")
end
I want to know if 4 is part of the array. It isent so expected output is Not in Array but Lua takes the number as the position of the entery, there is an entery on position 4 so the output is Is in Array
How can i check if a specific number is part of the array without indexing numbers as strings?
Your code doesn't do what you think it does. Let's walk through it:
local Array = {1, 8, 10, 15, 20, 30}
this is just syntactic sugar for
local Array = {[1] = 1, [2] = 8, [3] = 10, [4] = 15, [5] = 20, [6] = 30}
thus Array[4] is 15. This is how arrays work: You index an array using an index. An index is not to be confused with the value this gives you. In this example, 4 is the index and 15 is the value.
What you want isn't an array but rather a set. You can easily build a set in Lua by using the values as keys and using truthy values in a table:
local set = {[1] = true, [8] = true, [10] = true, [15] = true, [20] = true, [30] = true}
if you find this awkward to type, just write yourself an utility to turn an array into a set:
local function make_set(array)
local set = {}
for _, val in ipairs(array) do
set[val] = true
end
return set
end
set = make_set{1, 8, 10, 15, 20, 30}
You can then use this set to efficiently check whether it contains a number:
if set[number] then
print"is in set"
else
print"not in set"
end
Side notes:
Alternatively to building a set, you could use a linear search. This would be less efficient if done multiple times and isn't even much more convenient to implement. Lua makes the use of a "set" as a special case of the table very easy.
Uppercase in Lua is usually reserved for "class-like" tables, although there is no "official" naming convention.
If there is an array that contains random integers in ascending order, how can I tell if this array contains a arithmetic sequence (length>3) with the common differece x?
Example:
Input: Array=[1,2,4,5,8,10,17,19,20,23,30,36,40,50]
x=10
Output: True
Explanation of the Example: the array contains [10,20,30,40,50], which is a arithmetic sequence (length=5) with the common differece 10.
Thanks!
I apologize that I have not try any code to solve this since I have no clue yet.
After reading the answers, I tried it in python.
Here are my codes:
df = [1,10,11,20,21,30,40]
i=0
common_differene=10
df_len=len(df)
for position_1 in range(df_len):
for position_2 in range(df_len):
if df[position_1] + common_differene == df[position_2]:
position_1=position_2
i=i+1
print(i)
However, it returns 9 instead of 4.
Is there anyway to prevent the repetitive counting in one sequence [10,20,30,40] and also prevent accumulating i from other sequences [1,11,21]?
You can solve your problem by using 2 loops, one to run through every element and the other one to check if the element is currentElement+x, if you find one that does, you can continue form there.
With the added rule of the sequence being more than 2 elements long, I have recreated your problem in FREE BASIC:
DIM array(13) As Integer = {1, 2, 4, 5, 8, 10, 17, 19, 20, 23, 30, 36, 40, 50}
DIM x as Integer = 10
DIM arithmeticArrayMinLength as Integer = 3
DIM index as Integer = 0
FOR position As Integer = LBound(array) To UBound(array)
FOR position2 As Integer = LBound(array) To UBound(array)
IF (array(position) + x = array(position2)) THEN
position = position2
index = index + 1
END IF
NEXT
NEXT
IF (index <= arithmeticArrayMinLength) THEN
PRINT false
ELSE
PRINT true
END IF
Hope it helps
Edit:
After reviewing your edit, I have come up with a solution in Python that returns all arithmetic sequences, keeping the order of the list:
def arithmeticSequence(A,n):
SubSequence=[]
ArithmeticSequences=[]
#Create array of pairs from array A
for index,item in enumerate(A[:-1]):
for index2,item2 in enumerate(A[index+1:]):
SubSequence.append([item,item2])
#finding arithmetic sequences
for index,pair in enumerate(SubSequence):
if (pair[1] - pair[0] == n):
found = [pair[0],pair[1]]
for index2,pair2 in enumerate(SubSequence[index+1:]):
if (pair2[0]==found[-1] and pair2[1]-pair2[0]==n):
found.append(pair2[1])
if (len(found)>2): ArithmeticSequences.append(found)
return ArithmeticSequences
df = [1,10,11,20,21,30,40]
common_differene=10
arseq=arithmeticSequence(df,common_differene)
print(arseq)
Output: [[1, 11, 21], [10, 20, 30, 40], [20, 30, 40]]
This is how you can get all the arithmetic sequences out of df for you to do whatever you want with them.
Now, if you want to remove the sub-sequences of already existing arithmetic sequences, you can try running it through:
def distinct(A):
DistinctArithmeticSequences = A
for index,item in enumerate(A):
for index2,item2 in enumerate([x for x in A if x != item]):
if (set(item2) <= set(item)):
DistinctArithmeticSequences.remove(item2)
return DistinctArithmeticSequences
darseq=distinct(arseq)
print(darseq)
Output: [[1, 11, 21], [10, 20, 30, 40]]
Note: Not gonna lie, this was fun figuring out!
Try from 1: check the presence of 11, 21, 31... (you can stop immediately)
Try from 2: check the presence of 12, 22, 32... (you can stop immediately)
Try from 4: check the presence of 14, 24, 34... (you can stop immediately)
...
Try from 10: check the presence of 20, 30, 40... (bingo !)
You can use linear searches, but for a large array, a hash map will be better. If you can stop as soon as you have found a sequence of length > 3, this procedure takes linear time.
Scan the list increasingly and for every element v, check if the element v + 10 is present and draw a link between them. This search can be done in linear time as a modified merge operation.
E.g. from 1, search 11; you can stop at 17; from 2, search 12; you can stop at 17; ... ; from 8, search 18; you can stop at 19...
Now you have a graph, the connected components of which form arithmetic sequences. You can traverse the array in search of a long sequence (or a longest), also in linear time.
In the given example, the only links are 10->-20->-30->-40->-50.
So i opened a dataset and in short it looked something like this:
list1= ['Adrian,20,5,2000,green', 'Steve,15,6,1997,blue', ...]
trial = np.array(list1)
when i tried to print(trial[0][0]) to get Adrian, i only got the A.
So i figured i should make everything that has a comma after it an independent element, please help me get the output to be:
(['Adrian', 20, 5, 2000, 'green'], ['steve', 15, 6, 1997, 'blue'], ...)
where print(trial[0]) will give: ['Adrian', 20, 5, 2000, 'green']
and print(trial[0][0]) will give: Adrian
Just use the split function with a comma as the parameter like this:-
list2= ['Adrian,20,5,2000,green', 'Steve,15,6,1997,blue']
list1= []
for i in list2:
a = i.split(',')
list1 += [a]
trial = numpy.array(list1)
print(trial[0][0])
This will return Adrian.
You will still have to typecast the numbers to integer though, but that's easy to work around.
As the title suggests, I need to sort the rows of a certain matrix by one of its columns, preferably in place if at all possible. Said column contains Strings (the array being of type Array{Union{Float64,String}}), and ideally the rows should end up in an alphabetial order, determined by this column. The line
sorted_rows = sort!(data, by = i -> data[i,2]),
where data is my matrix, produces the error ERROR: LoadError: UndefKeywordError: keyword argument dims not assigned. Specifying which part of the matrix I want sorted and adding the parameter dims=2 (which I assume is the dimension I want to sort along), namely
sorted_rows = sort!(data[2:end-1,:], by = i -> data[i,2],dims=2)
simply changes the error message to ERROR: LoadError: ArgumentError: invalid index: 01 Suurin yhteinen tekijä ja pienin yhteinen jaettava of type String. So the compiler is complainig about a string being an invalid index.
Any ideas on how this type of sorting cound be done? I should say that in this case the string in the column can be expected to start with a number, but I wouldn't mind finding a solution that works in the general case.
I'm using Julia 1.1.
You want sortslices, not sort — the latter just sorts all columns independently, whereas the former rearranges whole slices. Secondly, the by function doesn't take an index, it takes the value that is about to be compared (and allows you to transform it in some way). Thus:
julia> using Random
data = Union{Float64, String}[randn(100) [randstring(10) for _ in 1:100]]
100×2 Array{Union{Float64, String},2}:
0.211015 "6VPQbWU5f9"
-0.292298 "HgvHLkufqI"
1.74231 "zTCu1U5Vdl"
0.195822 "O3j43sbhKV"
⋮
-0.369007 "VzFH2OpWfU"
-1.30459 "6C68G64AWg"
-1.02434 "rldaQ3e0GE"
1.61653 "vjvn1SX3FW"
julia> sortslices(data, by=x->x[2], dims=1)
100×2 Array{Union{Float64, String},2}:
0.229143 "0syMQ7AFgQ"
-0.642065 "0wUew61bI5"
1.16888 "12PUn4V4gL"
-0.266574 "1Z2ONSBP04"
⋮
1.85761 "y2DDANcFCe"
1.53337 "yZju1uQqMM"
1.74231 "zTCu1U5Vdl"
0.974607 "zdiU0sVOZt"
Unfortunately we don't have an in-place sortslices! yet, but you can easily construct a sorted view with sortperm. This probably won't be as fast to use, but if you need the in-place-ness for semantic reasons it'll do just the trick.
julia> p = sortperm(data[:,2]);
julia> #view data[p, :]
100×2 view(::Array{Union{Float64, String},2}, [26, 45, 90, 87, 6, 96, 82, 75, 12, 27 … 53, 69, 100, 93, 36, 37, 39, 8, 3, 61], :) with eltype Union{Float64, String}:
0.229143 "0syMQ7AFgQ"
-0.642065 "0wUew61bI5"
1.16888 "12PUn4V4gL"
-0.266574 "1Z2ONSBP04"
⋮
1.85761 "y2DDANcFCe"
1.53337 "yZju1uQqMM"
1.74231 "zTCu1U5Vdl"
0.974607 "zdiU0sVOZt"
(If you want the in-place-ness for performance reasons, I'd recommend using a DataFrame or similar structure that holds its columns as independent homogenous vectors — a Union{Float64, String} will be slower than two separate well-typed vectors, and sort!ing a DataFrame works on whole rows like you want.)
you may want to look at SortingLab.jls fast string sort functions.
]add SortingLab
using SortingLab
idx = fsortperm(data[:,2])
new_data = data[idx]
I have an array that looks contains say [6 5 7 7], however it is stored in ascii so it is [54 53 55 55]. I want to have it as the actual decimal values not ascii. I feel like the conversion back to decimal is simple, but I am unsure what the comman would be. thanks
If you have the ASCII values in an array called asciiValues you can do something like this:
var asciiValues = [54, 53, 55, 55];
var decimalValues = asciiValues.map(function(val) {
return Number(String.fromCharCode(val));
});
console.log(decimalValues); // [6, 5, 7, 7]
String.fromCharCode will take the ASCII code and return the string representation. You can then use the Number constructor to turn it into an actual number.
Assuming the array variable is named arr, the following statement will convert every element to a Number:
arr.map(Number);