Subtracting mean from calculation puts answer in list? - list

I have a function that cycles through two sperate lists and combines them into one as follows:
spread = Table[{gld[[i, 1]], (gld[[i, 2]] - gdx[[i, 2]]) },
{i, 1, Length[gld], 1}]
This works fine, and generates answers in the form:
{{2009, 6, 1}, 52.72}
But when I add a subtraction, as follows:
spread = Table[{gld[[i, 1]], (gld[[i, 2]] - gdx[[i, 2]]) - meanspread },
{i, 1, Length[gld], 1}]
I get answers in the format:
{{2009, 6, 1}, {-20.2896}}
This causes issues when I want to use DateLinePlot (all the data is in the extreme right of the graph, and the graph is not usable.
Can anyone suggest what might be happening here and how I may avoid it?
Thanks!

Most likely meanspread is not a number, but a single-item list, such as {1.1}. It's impossible to tell without knowing more details and having a sample of all data/variables you're using.

I don't get this, recreating your inputs as best I can. It really depends on how you're computing meanspread.
(*In[2]:= *)
gld = FinancialData["NYSE:GLD", "Close", {"June 1, 2009", DateString[], "Day"}];
gdx = FinancialData["NYSE:GDX", "Close", {"June 1, 2009", DateString[], "Day"}];
(*In[5]:= *)
First[spread = Table[{gld[[i, 1]], (gld[[i, 2]] - gdx[[i, 2]])}, {i, 1, Length[gld], 1}]]
(*Out[5]= *)
{{2009, 6, 1}, 52.72}
(*In[8]:= *)
meanspread = Mean[spread[[All, 2]]]
(*Out[8]= *)
74.0373
(*In[9]:= *)
First[Table[{gld[[i, 1]], (gld[[i, 2]] - gdx[[i, 2]]) - meanspread}, {i, 1, Length[gld], 1}]]
(*Out[9]= *)
{{2009, 6, 1}, -21.3173}

I think you would benefit from a simpler construction.
spread = {gld[[All, 1]], gld[[All, 2]] - gdx[[All, 2]] - meanspread}\[Transpose]
As already said, if meanspread is a single numerical value, and not a list, the output should be correct.

Related

Python Immutable Tuple - What Am I Doing Wrong?

Apologies if this is obvious but I'm pretty new to Python and I cannot get my head around this problem. In the following code I have populated a tuple with a series of lists and I am trying to create a new list with items from this tuple. I was hoping that the final result will be that test_raw remains unchanged and test_working will look like the following:
[['aa', 1, 2, 99.5, ['bb', 1, 2, 27.2]],
['aa', 5, 5, 74.2, ['bb', 5, 5, 37]]]
However, in the process, I seem to be appending the 'bb' lists to my tuple as well. I thought that once a tuple is constructed, it cannot be changed but obviously not. Any idea what is happening?
test_raw = (['aa',1,2,99.5],
['bb',1,2,27.2],
['aa',5,5,74.2],
['bb',5,5,37])
test_working = []
for i in range(len(test_raw)):
if test_raw[i][0] == "aa":
test_working.append(test_raw[i])
for i in range(len(test_raw)):
if test_raw[i][0] == "bb":
for j in range(len(test_working)):
if test_working[j][1:3] == test_raw[i][1:3]:
test_working[j].append(test_raw[i])
break
print(test_raw)
(['aa', 1, 2, 99.5, ['bb', 1, 2, 27.2]], ['bb', 1, 2, 27.2], ['aa',.....)
You are not appending to the tuple itself, but the lists inside tuple. I won't debug your code for you but when you run your code, you'll notice that your first list (originally ['aa',1,2,99.5]) has a new element in it (['bb', 1, 2, 27.2])
You aren't appending to the tuple, you are just changing the lists that are inside that tuple
Consider this simple example
my_tuple = (1,2,3, [4,5,6])
my_tuple[3].append(7)
This doesn't add onto my_tuple, just the list that is the last element of it

ValueError:[number] is not in the list, even though it is and the code i believe is correct

When i execute this testing code below, i get the error below it:
my_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
my_input = input("Pick a number from 1 to 10?")
number_index = my_numbers.index(my_input)
print(number_index)
ERROR-----
number_index = my_numbers.index(my_input) ValueError: '1' is not in
list
is this python? if so, look like is python 3, then the error is simple: input give you a string, and you have a list of integers and no integer is going to be equal to a string, ever, so when you pass my_input, a string, to index it search in the list my_numbers for a match but all the things inside it are integer so it fail and give the error. The solution is simple transform the input to a integer like this:
my_input = int( input("Pick a number from 1 to 10?") )
the same apply to other languages but the fine details may vary...

Evaluate expression using lists maxima

I'd like the result of the below maxima input to be [6,12,18] but it results in 2ac. Can anyone help?
a:2;
c:[1,2,3];
b:'(a*c);
''b;
a:3;
''b;
f:'(b*2);
''f;
I think ev(f, infeval) is what you want. See ? ev for info about infeval and other evaluation flags.
(%i1) c : [1, 2, 3];
(%o1) [1, 2, 3]
(%i2) b : '(a*c);
(%o2) a c
(%i3) a : 3;
(%o3) 3
(%i4) f : '(b*2);
(%o4) 2 b
(%i5) f;
(%o5) 2 b
(%i6) ''f;
(%o6) 2 a c
(%i7) ev (f);
(%o7) 2 a c
(%i8) ev (f, infeval);
(%o8) [6, 12, 18]
You can also write ev(f, infeval); as just f, infeval; at the input prompt.
That said, my advice is, don't try too hard to find tricky ways to evaluate stuff. It's easy to write something which has unexpected results and hard to understand. You'll have to find a balance between trying to get Maxima to do what your want, and accommodating Maxima's idiosyncrasies (i.e. changing your ideas to match Maxima's).
You should use f:'(''b*2);. This works as you expect.

Compact way to write a list of lists

I am writing a program that outputs a list of ordered lists of numbers. Say the output is as follows:
[1,1,1];
[1,1,2]
I would like to look at the output by eye and make some sense of it, but my output is hundreds to thousands of lines long. I would like to write the output in the following more compact format: [1,1,1/2], where the slash indicates that in the third slot I can have a 1 or a 2. So, for a longer example, [1/2, 1/3, 5, 8/9] would be the compact way of writing [1,1,5,8];[1,1,5,9];[1,3,5,8]; etc. Can anyone suggest a pseudocode algorithm for accomplishing this?
Edit: All of the lists are the same length. Also, I expect in general to have multiple lists at the end. For example {[1,1,2], [1,1,3], [1,2,4]} should become {[1,1,2/3], [1,2,4]}.
What'd I do is use a hash at each element in the first list. You'd then iterate through the remaining lists, and for each position in the other lists, you'd check against the hash in the first / original list for that index to see if you'd seen it before. So you'd end up with something like:
[1 : {1}, 1: {1, 3}, 5: {5}, 8: {8, 9}]
And then when printing / formatting the list, you'd just print each key in the hash, except you'd use slashes or whatever.
EDIT: Bad Psuedocode (python)(untested):
def shorten_list(list_of_lists):
primary_list = list_of_lists[0]
hash_values = [{} * len(primary_list)]
for i in range(len(list_of_lists)):
current_list = list_of_lists[i]
for j in range(current_list):
num = current_list[j]
if num not in hash_values[j]:
hash_values[j] = j
for i in range(len(hash_values)):
current_dict = hash_values[i]
print primary_list[i]
for key in current_dict:
if key != primary_list[i]:
print '/', key
Here's actual code to sort the lists the way you wanted. But maybe the most useful visualization would be a scatter plot. Import the data into your favorite spreadsheet, and plot away.
$(document).ready( function(){
var numbers = [
[1, 1, 5, 8],
[1, 1, 5, 9],
[1, 3, 5],
[1, 1, 5, 10, 15]];
$('#output').text(JSON.stringify(compactNumbers(numbers)));
});
function compactNumbers(numberlists){
var output = [];
for(var i = 0; i < numberlists.length; i++){
for(var j = 0; j < numberlists[i].length; j++) {
if(!output[j]) output[j] = [];
if($.inArray(numberlists[i][j], output[j]) == -1){
output[j].push(numberlists[i][j]);
}
}
}
return(output);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>

Specify Column and Row of a String Search

Because I'm working with a very complex table with nasty repeated values in variable places, I'd like to do a string search between specific rows and columns.
For example:
table={{"header1", "header2", "header3",
"header4"}, {"falsepositive", "falsepositive", "name1",
"falsepositive"}, {"falsepositive", "falsepositive", "name2",
"falsepositive"}, {"falsepositive", "falsepositive",
"falsepositive", "falsepositive"}}
%//TableForm=
header1 header1 header1 header1
falsepositive falsepositive name1 falsepositive
falsepositive falsepositive name2 falsepositive
falsepositive falsepositive falsepositive falsepositive
How do I look for a string, for example, in column three, rows one through two?
I'd like to use Which to assign values based on a string's location in the table.
E.g.,
Which[string matched in location one, value, matched in location two, value2]
As I understand it you want a test whether or not a given string is in a certain subsection of a matrix. You can pick these subsections using Part ([[...]]) and Span (;;), with which you can indicate ranges or subsamples of ranges. Testing whether or not this subsection contains your pattern can be done by MemberQ, like this:
MemberQ[table[[1 ;; 2, 3]], "name2"]
(* ==> False *)
MemberQ[table[[1 ;; 2, 3]], "header3"]
(* ==> True *)
In this way, your Which statement could look like this:
myVar =
Which[
MemberQ[table[[1 ;; 2, 3]], "name2"], 5,
MemberQ[table[[2 ;; 3, 4]], "falsepositive"], 6,
...
True, 20
]
Length[Cases[Position[table, "name1"], {1 | 2, 3}]] >= 1
Output -> True
Or
Cases[Position[table, "name1"], {1 | 2, 3}]
Output -> {{2, 3}}
Perhaps, if I understand you:
f[table_, value_, rowmin_, rowmax_, colmin_, colmax_] :=
Select[Position[table, value],
rowmin <= First## <= rowmax && colmin <= Last## <= colmax &]
f[table, "name1", 1, 10, 1, 10]
(*
-> {{2, 3}}
*)