1
$\begingroup$

I have written a code:

x={0,0,0,1,1,2}

For[i = 0, 
    i < Length[DeleteCases[Flatten[Differences[#] & /@ Partition[x, 2, 1]],0]]+ 1, 
    i++; 
    For[j = 1, x[[i + 1]] == x[[i]], j++; 
       If[x[[i + 1]] == x[[i]], x = Drop[x, {i + 1}], x = x] 
       x]
  ]

and when i type x the output is

{0,1,2}

now i want to put the loop in the function and i have done below

f100[x_] := (
 For[i = 0, 
     i < Length[DeleteCases[Flatten[Differences[#] & /@ Partition[x, 2, 1]],0]] + 1, 
     i++; 
      For[j = 1, x[[i + 1]] == x[[i]], j++; 
        If[x[[i + 1]] == x[[i]], x = Drop[x, {i + 1}], x = x] 
         x]
    ]; 
    x)

but when i type

f100[{0,0,0,1,1,2}]

It has "Lists {0,0,0,1,1,2} and {0,0,1,1,2} are not the same shape."

and i use

SetAttributes[f100, HoldFirst];

but it is failed too. how can i do?

$\endgroup$

2 Answers 2

3
$\begingroup$

You can't assign values to an input variable of a function.

f100[y_] := (x = y; 
  For[i = 0, 
   i < Length[
      DeleteCases[Flatten[Differences[#] & /@ Partition[x, 2, 1]], 
       0]] + 1, i++;
   For[j = 1, x[[i + 1]] == x[[i]], j++;
    If[x[[i + 1]] == x[[i]], x = Drop[x, {i + 1}], x = x] x]];
  x)
$\endgroup$
0
$\begingroup$

As far as I understand, you are deleting duplicates from your list. Have you tried with DeleteDuplicates[]?

DeleteDuplicates[{0,0,0,1,1,2}]]
(* {0,1,2} *)

If you are interested in removing successive duplicates only, have a look at Remove Successive Duplicate From A Large List (200k by 4 matrix).

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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