Related
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Given a string: "ABCD", return the substrings with one or more missing characters keeping the order of the strings. This doesn't seem to be a "permutation", but I'm not sure if this algorithm has a name. I am using this to generate anagrams of a word and words within a word.
Example:
A
B
C
D
AB
BC
CD
AC
AD << missing BC
ABC
BCD
ACD
ABD
You're generating the ordered power set of the characters of the input string - meaning, all the subsets you can get from the set of characters in the input string, preserving the initial order:
input = { A, B, C, D }
output = { {}, {A}, {B}, {C}, {D}, {A, B}, {B, C} {C, D}, {A, C}, {A, D},
{B, D}, {A, B, C}, {A, B, D}, {A, C, D}, {B, C, D}, {A, B, C, D} }
The resulting set has 2^n elements (with n being the size of the input set), you might want to remove the empty set and the input set from the result, but basically this is the algorithm you're looking for. It's easy to find implementations for any language you want.
Simple question, given a list like this
Clear[a, b, c, d, e, f];
lst = {{a, b}, {c, d}, {e, f}};
and suppose I have a function defined like this:
foo[x_,y_]:=Module[{},...]
And I want to apply this function to the list, so If I type
Map[foo, lst]
This gives
{foo[{a, b}], foo[{c, d}], foo[{e, f}]}
I want it to come out as
{foo[a, b], foo[c, d], foo[e, f]}
so it works.
What is the best way to do this? Assume I can't modify the function foo[] definition (say it is build-in)
Only 2 ways I know now are
Map[foo[#[[1]], #[[2]]] &, lst]
{foo[a, b], foo[c, d], foo[e, f]}
(too much work), or
MapThread[foo, Transpose[lst]]
{foo[a, b], foo[c, d], foo[e, f]}
(less typing, but need to transpose first)
Question: Any other better ways to do the above? I looked at other Map and its friends, and I could not see a function to do it more directly than what I have.
You need Apply at Level 1 or its short form, ###
foo###lst
{foo[a, b], foo[c, d], foo[e, f]}
One possible way is to change head of each element of lst from List to foo:
foo ## # & /# lst
{foo[a, b], foo[c, d], foo[e, f]}
Just to report puzzling performance tests of the both methods (###, ## # & /#) :
T = RandomReal[{1,100}, {1000000, 2}];
H[F_Symbol, T_List] :=
First#AbsoluteTiming[F ### T;]/First#AbsoluteTiming[F ## # & /# T;]
Table[{ToString[F], H[F, T]}, {F, {Plus, Subtract, Times, Divide, Power, Log}}]
Out[3]= {{"Plus", 4.174757},
{"Subtract", 0.2596154},
{"Times", 3.928230},
{"Divide", 0.2674164},
{"Power", 0.3148629},
{"Log", 0.2986936}}
These results are not random, but roughly proportional for very different data sizes.
### is roughly 3-4 times faster for Subtract, Divide, Power, Log while ## # & /# is 4 times faster for Plus and Times giving rise to another questions, which (as one can believe) could be slightly
clarified by the following evaluation:
Attributes#{Plus, Subtract, Times, Divide, Power, Log}
Only Plus and Times have attributes Flat and Orderless, while among the rest only Power (which seems relatively the most efficient there) has also an attribute OneIdentity.
Edit
A reliable explanation to observed performance boosts (thanks to Leonid Shifrin's remarks) should go along a different route.
By default there is MapCompileLength -> 100 as we can check evaluating SystemOptions["CompileOptions"].
To reset autocompilation of Map we can evaluate :
SetSystemOptions["CompileOptions" -> "MapCompileLength" -> Infinity]
Now we can test relative performance of the both methods by evaluating once more our H - performance testing function on related symbols and list :
Table[{ToString[F], H[F, T]}, {F, {Plus, Subtract, Times, Divide, Power, Log}}]
Out[15]= {{"Plus", 0.2898246},
{"Subtract", 0.2979452},
{"Times", 0.2721893},
{"Divide", 0.3078512},
{"Power", 0.3321622},
{"Log", 0.3258972}}
Having these result we can conclude that in general Yoda's approach (###) is the most efficient, while that provided by Andrei is better in case of Plus and Times due to automatic compilation of Map allowing better performance of (## # & /#).
A few more possibilities to pick from:
This one is a more verbose version of yoda's answer. It applies foo at level 1 of the list lst only (replaces the head List with the head foo):
Apply[foo, lst, {1}]
This does the same, but maps Apply over the list lst (essentially Andrei's answer):
Map[Apply[foo, #] &, lst ]
And this just replaces the pattern List[x__] with foo[x] at level 1:
Replace[lst, List[x__] -> foo[x], 1]
The answers on Apply[] are spot on, and is the right thing to do, but what you were trying to do, was to replace a List[] head with a Sequence[] head, i.e. List[List[3,5],List[6,7]] should become List[Sequence[3,5],Sequence[6,7]].
Sequence head is what naturally remains if a head of any list of parameters is deleted, so Delete[Plus[3,5],0] and Delete[{3,5},0] and Delete[List[3,5],0] would all produce Sequence[3,5].
So foo#Delete[#,0]&/#{{a, b}, {c, d}, {e, f}} will give you the same as foo###{{a, b}, {c, d}, {e, f}}.
Alternatively, foo[#/.List->Sequence]&/#{{a, b}, {c, d}, {e, f}} does the same thing.
I need to build a partial Inverted Index. Something like:
l = {{x, {h, a, b, c}}, {y, {c, d, e}}}
iI[l]
(*
-> {{a, {x}}, {b, {x}}, {c, {x, y}}, {d, {y}}, {e, {y}}, {h, {x}}}
*)
I think it is pretty clear what it does. In the input list, the {x, y ...} are unique, while the {a, b, c, ..} are not. The output ought to be ordered by #[[1]].
Right now, I am doing this:
iI[list_List] := {#, list[[Position[list, #][[All, 1]]]][[All, 1]]} & /#
(Union#Flatten#Last#Transpose#list)
But it looks too convoluted for such an easy task, seems too slow, and I should be able to cope with Legion.
A test drive to compare your results:
words = DictionaryLookup[];
abWords = DictionaryLookup["ab" ~~ ___];
l = {#, RandomChoice[abWords, RandomInteger[{1, 30}]]} & /# words[[1 ;; 3000]];
First#Timing#iI[l]
(*
-> 5.312
*)
So, any ideas for an speedup?
Seems a classic task for Reap-Sow (improvement in the final version due to #Heike):
iI[list_] := Sort[Reap[Sow ### list, _, List][[2]]]
Then,
iI[l]
{{a, {x}}, {b, {x}}, {c, {x, y}}, {d, {y}}, {e, {y}}, {h, {x}}}
and
In[22]:=
words=DictionaryLookup[];
abWords=DictionaryLookup["ab"~~___];
l={#,RandomChoice[abWords,RandomInteger[{1,30}]]}&/#words[[1;;3000]];
First#Timing#iI[l]
Out[25]= 0.047
EDIT
Here is an alternative version with a similar (slightly worse) performance:
iIAlt[list_] :=
Sort#Transpose[{#[[All, 1, 2]], #[[All, All, 1]]}] &#
GatherBy[Flatten[Thread /# list, 1], Last];
It is interesting that Reap - Sow here gives an even slightly faster solution than the one based on structural operations.
EDIT 2
Just for an illustration - for those who prefer rule-based solutions, here is one based on a combination of Dispatch and ReplaceList:
iIAlt1[list_] :=
With[{disp = Dispatch#Flatten[Thread[Rule[#2, #]] & ### list]},
Map[{#, ReplaceList[#, disp]} &, Union ## list[[All, 2]]]]
It is about 2-3 times slower than the other two, though.
How can I get the indices of a selection rather than the values. I.e.
list={3->4, 5->2, 1->1, 5->8, 3->2};
Select[list, #[[1]]==5&]; (* returns {5->2, 5->8} *)
I would like something like
SelectIndices[list, #[[1]]==5&]; (* returns {2, 4} *)
EDIT: I found an answer to the immediate question above (see below), but what about sorting. Say I want to sort a list but rather than returning the sorted list, I want to return the indices in the order of the sorted list?
Ok, well, I figured out a way to do this. Mathematica uses such a different vocabulary that searching the documentation still is generally unfruitful for me (I had been searching for things like, "Element index from Mathematica Select", to no avail.)
Anyway, this seems to be the way to do this:
Position[list, 5->_];
I guess its time to read up on patterns in Mathematica.
WRT to the question remaining after your edit: How about Ordering?
In[26]:= Ordering[{c, x, b, z, h}]
Out[26]= {3, 1, 5, 2, 4}
In[28]:= {c, x, b, z, h}[[Ordering[{c, x, b, z, h}]]]
Out[28]= {b, c, h, x, z}
In[27]:= Sort[{c, x, b, z, h}]
Out[27]= {b, c, h, x, z}
I think you want Ordering:
Sort[list, #[[1]] == 5 &]
Ordering[list, All, #[[1]] == 5 &]
(*
{5->2,5->8,3->2,1->1,3->4}
{2,4,5,3,1}
*)
Sorry, I had read your question to fast.
I think your second question is about how to sort the list according to the values of the rules. The simplest way that come to mind is by using a compare function. then simply use your solution to retrieve the indices:
comp[_ -> x_, a_ -> y_] := x < y;
Position[Sort[list, comp], 5 -> _]
Hope this helps!
Without sorting or otherwise altering the list, do this:
SelectIndex[list_, fn_] := Module[{x},
x = Reap[For[i = 1, i < Length[list], i++, If[fn[list[[i]]], Sow[i], Null];]];
If[x[[1]] == {}, {}, x[[2, 1]]]]
list={ {"foo",1}, {"bar",2}};
SelectIndex[list, StringMatchQ[ #[[1]], "foo*"] &]
You can use that to extract records from a database
Lookup[list_, query_, column_: 1, resultColumns_: All] := list[[SelectIndex[list, StringMatchQ[query, #[[column]]] &], resultColumns]]
Lookup(list,"foo")
I am wondering how I can write a function to be used in the Apply function in Mathematica? For example, I want to trivially re-implement the Or function, I found the following
Apply[(#1 || #2)&,{a,b,c}]
is not okay since it only Or'ed the first two elements in the list. Many thanks!
This will work, no matter how many vars, and is a general pattern:
Or[##]&,
for example
In[5]:= Or[##] & ## {a, b, c}
Out[5]= a || b || c
However, in the case of Or, this is not good enough, since Or is HoldAll and short-circuiting - that is, it stops upon first True statement, and keeps the rest unevaluated. Example:
In[6]:= Or[True, Print["*"]]
Out[6]= True
In[7]:= Or[##] & ## Hold[True, Print["*"]]
During evaluation of In[7]:= *
Out[7]= True
This will be ok though:
Function[Null,Or[##],HoldAll],
for example,
In[8]:= Function[Null, Or[##], HoldAll] ## Hold[True, Print["*"]]
Out[8]= True
and can be used in such cases (when you don't want your arguments to evaluate). Note that this uses an undocumented form of Function. The mention of this form can be found in the book of R.Maeder, "Programming in Mathematica".
HTH
Or ## {a, b, c}
Equivalent
Apply[Or, {a, b, c}]
Equivalent
{a, b, c} /. {x_, y__} -> Or[x, y]
Apply works like this:
{2 #1, 3 #2, 4 #3} & ## {a, b, c}
{2 a, 3 b, 4 c}
Plus[2 #1, 3 #2, 4 #3] & ## {a, b, c}
2 a + 3 b + 4 c
Are you sure you are expecting the right thing from Apply? If you look in the documentation, http://reference.wolfram.com/mathematica/ref/Apply.html, you will see that Apply[f,expr] simply replaces the head of f by expr. It does not, in general, give f[expr].
If you wish to operate with function f onto expr, try f#expr or f[expr].
Perhaps you understand the above and your question really is, "how do I define some f that, when I do Apply[f,{a,b,c}], does the same job as Or[a,b,c]. Is that it?