3
$\begingroup$

Let L be a list of several lists. And the length of each list is less than 1000.

You can create L by

L = Table[ConstantArray[1, RandomInteger[999]], 100000];

For example, let L looks like

{a list whose length is 340,  
 a list whose length is 525,  
 a list whose length is 829,  
 a list whose length is 422, 
......}

What I want to get is a list of integers

   M = {3, 5, 8, 4,......}

That is, if the length of an element is
between 0~99, assign 0,
between 100~199, assign 1,
...
between 900~999, assign 9.

In fact this can be done easily by Floor[Length[#]/100]&/@L

But I want to achieve it by built-in Replace.

Here is the code I did my best :

Replace[L, Table[_?(Length[#] < 100 k &) -> k - 1 /. k -> a, {a, 1, 10}], {1}] (*code of an  interest*)

But there is one thing I don't like about this code algorithmically.
This code computes Length[#] too often.
(Length is very fast, so just lucky this time.
What if the function is so slow.)
I want the Length to be computed only once for each element.

I tried codes like :

Replace[L, Module[{Leng}, Leng = Hold[Length[#]]; 
  Table[_?(Leng < 100 k &) -> T[k] /. k -> a, {a, 10}]], {1}] (*failed code*)

I tried Module,Block,With... all failed. Can you help me?
By modifying *code of an interest* slightly, can you show a code that computes Length only once for each element?

$\endgroup$
3
  • 4
    $\begingroup$ Is there a reason that you are so insistent on using Replace? Map seems like a natural thing to do here: Quotient[Length@#, 100] & /@ L. I would post that as the answer except that you seem to really want Replace. $\endgroup$
    – lericr
    Commented May 13, 2022 at 13:27
  • $\begingroup$ Because.. If pattern1 matches then replace it to object1, If pattern2 matches then replace it to object2, If pattern3 match esthen replace it to object3... We can deal with this general problem. $\endgroup$
    – imida k
    Commented May 14, 2022 at 4:02
  • $\begingroup$ Thank you, the example In my post was simple which means lucky enough to achieve the purpose with a short code. Here is my original intention and motivation : mathematica.stackexchange.com/questions/268227/… $\endgroup$
    – imida k
    Commented May 14, 2022 at 4:07

1 Answer 1

5
$\begingroup$
L = Table[ConstantArray[1, RandomInteger[999]], 100000];

m = Replace[L, {x_List :> Quotient[Length@x, 100]}, {1}];

$$\{7,2,8,8,6,5,1,5,2,1,1,3,6,7,2,4,7,2,1,8,2,3,8,6,5,2,0,7,4,9,6,3,2,4,6,5,7,7,9,9,\langle\langle 99920\rangle\rangle ,1,7,8,6,2,5,1,0,8,7,3,6,2,8,4,8,9,0,5,6,4,4,9,6,4,7,1,2,7,0,1,4,1,1,0,7,9,0,4,4\}$$

$\endgroup$
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.