Message Boards Message Boards

0
|
5777 Views
|
8 Replies
|
3 Total Likes
View groups...
Share
Share this post:

Iterate a variable n as a levelspec in Replace ?

Posted 7 years ago

In the fuction Replace[expr,rules,levelspec], levelspec may be a variable: Given:

g = {{{a, b}}, {a, b}, c}
locVar = {a, b}
Replace[g, locVar -> 10, 1]

Here 1 is the levelspec, run Replace[g, locVar -> 10, 1] will:

{{{a, b}}, 10, c};

run

Replace[g, locVar -> 10, 2] :
{{10}, 10, c}
Replace[g, locVar -> 10, n] /. n -> {1, 2}:
{{10}, 10, c}

But how to iterate n? run

Do[Replace[g, locVar -> 10, n], {n, 1, 2}]

, no result,why?

POSTED BY: Math Logic
8 Replies
Posted 7 years ago

Excellent! You are really smart! :)

POSTED BY: Updating Name

To be more illustrative, I modify the initial example:

In[1]:= g = {{{{{{{a, b}}}}}}, {{{{a, b}}}}, {{{a, b}}}, {{a, b}}, {a, b}, c};
locVar = {a, b};
Table[Replace[g, locVar -> 10, n], {n, 1, Depth[g]}]

Out[1]= {{{{{{{{a, b}}}}}}, {{{{a, b}}}}, {{{a, b}}}, {{a, b}}, 10, c},
{{{{{{{a, b}}}}}}, {{{{a, b}}}}, {{{a, b}}}, {10}, 10, c},
{{{{{{{a, b}}}}}}, {{{{a, b}}}}, {{10}}, {10}, 10, c},
{{{{{{{a, b}}}}}}, {{{10}}}, {{10}}, {10}, 10, c},
{{{{{{{a, b}}}}}}, {{{10}}}, {{10}}, {10}, 10, c},
{{{{{{10}}}}}, {{{10}}}, {{10}}, {10}, 10, c},
{{{{{{10}}}}}, {{{10}}}, {{10}}, {10}, 10, c},
{{{{{{10}}}}}, {{{10}}}, {{10}}, {10}, 10, c}}
Posted 7 years ago

If the range of levelspec n is not determined, how to use Table[Replace[g, locVar -> 10, n], {n, 1, 2}]? I.e., Here, the maximum 2 is known as a constant, if it not known to be fixed, how to iterate Replace even in Table function?

POSTED BY: Math Logic

If you don't want to keep separate levels, then you can simply wright:

In[1]:= g = {{{a, b}}, {a, b}, c};
locVar = {a, b};
Replace[g, locVar -> 10, 2]

Out[3]= {{10}, 10, c}

that means rule application up to second level.

Posted 7 years ago

Table[Replace[g, locVar -> 10, {1, 2}]] :{{10}, 10, c}

It's OK? Appreciated?

POSTED BY: Math Logic

Hi Yinsheng, if you want to apply Replace on multiple levels at once you can also specify levelspec as {a,b} such that is will replace on levels a to b. If you want to keep separate levels, use Valeriu's answer.

POSTED BY: Sander Huisman

Try Table[]:

In[1]:= g = {{{a, b}}, {a, b}, c};
locVar = {a, b};
Table[Replace[g, locVar -> 10, n], {n, 1, 2}]

Out[3]= {{{{a, b}}, 10, c}, {{10}, 10, c}}
Posted 7 years ago

Good? Got it by your answer!!Thanks!!!

POSTED BY: Math Logic
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract