Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.soft-sys.math.mathematica > #16078 > unrolled thread

Re: Exercise of Programming with Mathematica

Started bySseziwa Mukasa <mukasa@gmail.com>
First post2013-10-19 07:46 +0000
Last post2013-10-19 07:46 +0000
Articles 1 — 1 participant

Back to article view | Back to comp.soft-sys.math.mathematica

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Exercise of Programming with Mathematica Sseziwa Mukasa <mukasa@gmail.com> - 2013-10-19 07:46 +0000

#16078 — Re: Exercise of Programming with Mathematica

FromSseziwa Mukasa <mukasa@gmail.com>
Date2013-10-19 07:46 +0000
SubjectRe: Exercise of Programming with Mathematica
Message-ID<l3tdcc$9tb$1@smc.vnet.net>
I can't determine a pattern that represents a pair which does not also match {{a,b},{c,d}}, but I can think of two options.  The first is not to use pattern matching at all, which may be more efficient anyway:

In[5]:= {{a, b}, {c, d}, {e, f}}[[All, {2, 1}]]
{{a, b}, {c, d}}[[All, {2, 1}]]
Out[5]= {{b, a}, {d, c}, {f, e}}
Out[6]= {{b, a}, {d, c}}

The other is to limit the pattern matching to the appropriate level:

In[21]:= Replace[{{a, b}, {c, d}, {e, f}}, {x_, y_} -> {y, x}, {1}]
Replace[{{a, b}, {c, d}}, {x_, y_} -> {y, x}, {1}]
Out[21]= {{b, a}, {d, c}, {f, e}}
Out[22]= {{b, a}, {d, c}}

Elegance as always is in the eye of the beholder,

Sseziwa

On Oct 18, 2013, at 4:45 AM, Zhenyi Zhang <infozyzhang@gmail.com> wrote:

> Here is a rule designed to switch the order of each pair of expressions in a list. It works fine on the
> first example, but fails on the second.
> In[1]:= {{a, b}, {c, d}, {e, f}}/.{x_, y_} :> {y, x}
> Out[1]= {{b, a}, {d, c}, {f, e}}
> In[2]:= {{a, b}, {c, d}}/.{x_, y_} :> {y, x}
> Out[2]= {{c, d}, {a, b}}
> Explain what has gone wrong and rewrite this rule to correct the situation, that is, so that the second
> example returns {{b, a}, {d, c}}
>
> My solution is the most stupid one.
>
> {{a, b}, {c, d}}/.{{x_, y_}, {w_, t_}} :> {{y, x}, {t, w}}
>
> May I ask any elegant solutions?
>
> Thanks.
>

[toc] | [standalone]


Back to top | Article view | comp.soft-sys.math.mathematica


csiph-web