Re: the simplest way?
- To: mathgroup at smc.vnet.net
- Subject: [mg16446] Re: [mg16350] the simplest way?
- From: Andrzej Kozlowski <andrzej at tuins.ac.jp>
- Date: Sat, 13 Mar 1999 02:21:52 -0500
- Sender: owner-wri-mathgroup at wolfram.com
On Thu, Mar 11, 1999, Antoine Zahnd <antoine.zahnd at iprolink.ch> wrote: >Hello, > >I have two questions with lists, each time to avoid the Length function. > > >1) For example, how to write a function that will go thru the elements of a >list of >integers, and will return False as soon as an odd number is found, without >using >Length? > > >With Length it is easy, but not so clean ... >f[l_]:= Block[{k},For[k=1,k<=Length[l],k++,If[OddQ[l[[k]]],Return[True]]]; >False]; > > >2) Is it possible to write the following function without Length? > >l={1,2,3}; >Table[ReplacePart[l,l[[i]]-1,i],{i,1,Length[l]}] >{{0,2,3},{1,1,3},{1,2,2}} > >More generally, is there a way to write something like: >(for x in l ... collect (f x) ) , and the collection of the (f x) are >returned >in a list? > >I don't see how to write a Lisp style dolist function in Mathematica >without the Length! > >Hope that the questions make sens ... > >Thank you very much for your help. > >antoine.zahnd at iprolink.ch > > In cases like your first one I like to use Scan because it is so efficient. For example, the foillwoing function will scan a list and return True as soon as it finds an odd number. In[1]:= g[l_]:=Scan[If[OddQ[#],Return[True]]&,l] On my PowerBook G3 it is about twice as fast as your f. For example, lets consider a long list In[2]:= l=Join[Range[0,100000,2],Table[Random[Integer,{1,9}],{50}]]; In[3]:= g[l]//Timing Out[3]= {1.18333 Second,True} While with your f In[4]:= f[l_]:= Block[{k},For[k=1,k<=Length[l],k++,If[OddQ[l[[k]]],Return[True]]]; False]; In[5]:= f[l]//Timing Out[5]= {2.7 Second,True} The only difference is that if your list contains no odd numbers g will not return anything while f will return False. If you insist on having that property you might prefer a function like h=If[Position[#,_?OddQ,1]=!={},True,False]&; Now In[22]:= h[l] Out[22]= True While In[23]:= h[{2,4}] Out[23]= False To my surprise I just discovered that h beats g in this case for speed: In[27]:= h[l]//Timing Out[27]= {0.5 Second,True} I was surprised for in my experience Scan has usually been much faster than Position. Turning to your second example, you can simply modify your solution using Map; In[32]:= Map[ReplacePart[l,l[[#]]-1,l[[#]]]&,l] Out[32]= {{0,2,3},{1,1,3},{1,2,2}} This is also, I think, the way to answer your remaining questions. Andrzej Kozlowski Toyama International University JAPAN http://sigma.tuins.ac.jp/ http://eri2.tuins.ac.jp/