0
$\begingroup$

I'm trying to use If and AppendTo to create a list by imposing conditions on an initial list. And I'm getting an error that "the expression n cannot be used as a part specification."

X = Tuples[{0, 1}, 4];
B = {};
If[Length[Subsets[X][[n]]] = 2, 
   AppendTo[B, Mod[Total[Subsets[X][[n]]], 2]], {n, 1, 100}
  ];

There must be a very simple mistake I'm making here right? Obviously, the elements of Subsets[X] are subsets of the set X. So I'm trying to select those of length 2, and then record that simple expression in a new list.

$\endgroup$
2
  • 2
    $\begingroup$ There might be better way to do this without using appendto. But first you need to find the = to make it == in Length[Subsets[X][[n]]] = 2 And also you need to use Table. Something like this Table[If[Length[Subsets[X][[n]]] == 2, AppendTo[B, Mod[Total[Subsets[X][[n]]], 2]] ], {n, 1, 100} ] but again, this slow $\endgroup$ – Nasser Feb 1 '20 at 22:55
  • 1
    $\begingroup$ Given your initial X, what are you trying to get? And, I presume you have seen that Subsets may take an argument so you could use Subsets[X,{2}] to get all subsets of X with length 2. $\endgroup$ – Mark R Feb 2 '20 at 0:05
1
$\begingroup$

Is this what you want?

Mod[Total /@ Subsets[X, {2}], 2]

If you really only want to consider the first 100, you can use MapIndexed instead.

$\endgroup$
1
$\begingroup$
B2 = Mod[Total[Subsets[X, {2}], {2}], 2]

Compare with B

B == B2[[;; Length@B]] 

True

where B is obtained from corrected version of your code:

X = Tuples[{0, 1}, 4];
B = {};
Do[If[Length[Subsets[X][[n]]] == 2, 
   AppendTo[B, Mod[Total[Subsets[X][[n]]], 2]]], {n, 1, 100}];
$\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.