Hi I have a list of numbers for example k_1,k_2,...k_n, and f is a function. Now I apply f on the list of numbers and I need those numbers such that f is increasing,i.e.
f(k_i)>f(k_j) for any i>j .
I can get the results number k_i's each in different line, but I need the results in one table separated with comma or something else and counting the number of results.
For example:
k = Table[k1, k2, k3, k4, k5, k6, k开发者_开发技巧7, k8, k9, k10];
count = 0;
i=1;
For[j = i, j <= 10, j++,
If[f[k[[j]]] - f[k[[i]]] > 0, i = j; Print["k", i];
count = count + 1]];
Print["count= ", count]
I got the result like:
k2
k3
k5
k9
count=4
but I need the results to be together:
{k2,k3,k5,k9}
count=4
any idea?
thanks
Instead of Print
, you could do AppendTo
, ie
list={};AppendTo[list,5]
It might be good to start learning functional programming approach as Mathematica has tools to make it efficient, your above code might look something like this
pairs = Partition[list, 2, 1];
increasingPairs = Select[pairs, f[First[#]] < f[Last[#]] &];
Last /@ increasingPairs
You seem to want the longest increasing subsequence. The simplest and most efficient way I am aware of to get it in Mathematica is the following:
lis[f_, vals_List] := LongestCommonSequence[#, Sort[#]] &[Map[f, vals]];
Example:
In[8]:= lis[# &, {5, 3, 6, 1, 5, 7}]
Out[8]= {5, 6, 7}
In principle, the answer is not unique - there may be several different longest increasing subsequences with the same length.
精彩评论