Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.soft-sys.math.mathematica > #12897
| From | Fred Simons <f.h.simons@tue.nl> |
|---|---|
| Newsgroups | comp.soft-sys.math.mathematica |
| Subject | Re: Applying "Replace" to subsets of lists |
| Date | 2012-12-20 08:18 +0000 |
| Message-ID | <kauhle$in2$1@smc.vnet.net> (permalink) |
| References | <20121219095527.0EEB0692F@smc.vnet.net> |
| Organization | Time-Warner Telecom |
Since you want to replace the second b, no matter on what level it
occurs, I think you need a counter:
In[3]:= n=0; {{b,2},b} /. {b :> (n=n+1;If[n==2,1,b])}
Out[3]= {{b,2},1}
In[4]:= n = 0; {{b, 2}, 3 + b + b^2} /. {b :> (n = n + 1; If[n == 2, 1,
b])}
Out[4]= {{b, 2}, 4 + b^2}
Regards,
Fred Simons
Eindhoven University of Technology
Op 19-12-2012 10:55, abed.alnaif@gmail.com schreef:
> Hello,
> Say I have the following list, and I'd like to replace the second 'b' with the value 1, leaving the first b untouched:
>
> MagicFunction[{{b, 2}, b}] = {{b, 2}, 1}
>
> How do I do this? I've tried the following:
>
> This doesn't work since it replaces both 'b'
> In: {{b, 2}, b} /. b -> 1
> Out: {{1, 2}, 1}
>
> This doesn't work (I'm not sure why):
> In: {{b, 2}, b} /. {{x_, y_}, f_[b]} -> {{x, y}, 1, f[1]}
> Out: {{b, 2}, b}
>
> This works:
> In: {{b, 2}, b} /. {{x_, y_}, b} -> {{x, y}, 1}
> Out: {{b, 2}, 1}
>
> However, 'b' may appear in different forms, in which case the previous approach fails:
> In: {{b, 2}, b^2} /. {{x_, y_}, b} -> {{x, y}, 1}
> Out: {{b, 2}, b^2}
>
> Using the 'levelspec' argument of 'Replace' also fails since 'b' can appear in different forms:
> In: Replace[{{b, 2}, b^2}, b -> 1, 1]
> Out: {{b, 2}, b^2}
> In: Replace[{{b, 2}, b^2}, b -> 1, 2]
> Out: {{1, 2}, 1}
>
> Thank you,
>
> Abed
>
Back to comp.soft-sys.math.mathematica | Previous | Next | Find similar | Unroll thread
Re: Applying "Replace" to subsets of lists Fred Simons <f.h.simons@tue.nl> - 2012-12-20 08:18 +0000
csiph-web