1
$\begingroup$

My question is about the use of "Which" inside "Do". More precisely, I have written these two pieces of code, which I think should give the same answer. I define a list:

part = {{a, b}, {c, d}, {e, f}, {g, h}}
lenpart=Length[part];

Then I print the elements of the list. I do it first like this:

Do[Which[
ipart==1,
Print[part[[ipart]]],
ipart!=1 && ipart!=lenpart,
Print[part[[ipart]]],
ipart==lenpart,
Print[part[[ipart]]]
],{ipart,1,lenpart}];

This one prints all the elements of the list, as I would expect. Then I do it in this way:

Do[Which[
ipart==First[part],
Print[ipart],
ipart!=First[part] && ipart!=Last[part],
Print[ipart],
ipart==Last[part],
Print[ipart]
],{ipart,part}];

This one, instead, prints only {a,b}, but it seems to me that they should give the same output. I am using Mathematica 10.2.0.0 on Mac OSX.

$\endgroup$
2
$\begingroup$

The Problem is that mathematica does not know if {a,b}!={c,d}. So this is not evaluated as true since c could be the same value as a, and so on.

Table[ipart != {a, b}, {ipart, part}]

{False, {c, d} != {a, b}, {e, f} != {a, b}, {g, h} != {a, b}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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