Jorge Cabrera
Jorge Cabrera

Reputation: 341

Comparing two lists in Mathematica

i'm doing a program that given two lists and if part of one list is equivalent to the other entire list, then return the other part of the list. Difficult to explain, i'll leave the code here

E8[L_, P_] := Module[{},
  final = {};
  For[i = 1, i <= Length[L], i++,
   ok = True;
   For[j = 1, j <= Length[P], j++,
    If[L[[i, j]] != P[[j]], 
     ok = False
     ]
    ];
   If[ok == True, 
    coin = Take[L[[i]], {Length[P] + 1, Length[L[[i]]]}];
    AppendTo[final, coin]
    ]
   ];
  Return[final]
  ]

L = {{a, b, a}, {a, b, b}, {b, b, p}, {a, b, a, a}};
P = {a, b};
E8[L, P]

Out={{a}, {b}, {p}, {a, a}

For some reason the program is evaluating as True the {b,b,p} and not assigning ok=False. I need help with that. Thanks

Edit: I just need to find out why ok is not assigning False in that part of the code

If[L[[i, j]] != P[[j]], 
 ok = False
 ]

For sure the problem is there. I tried changing words {a,b} for numbers and the program is running properly, but when i try to compare words, it doesn't work. How could i compare lists with words?

Upvotes: 2

Views: 3362

Answers (2)

Chris Degnen
Chris Degnen

Reputation: 8655

You should use UnsameQ to test whether two expressions are not identical.

UnsameQ[L[[i, j]], P[[j]]]

or in the shorthand form

L[[i, j]] =!= P[[j]]

(This avoids changing the expressions being tested, as ToString does.)

In more Mathematica style your code could be written like this:-

e8[listL_, listP_] := Module[{plen = Length[listP]},
  DeleteCases[
   Map[If[SameQ[Take[#, plen], listP], Drop[#, plen]] &, listL],
   Null]]

listL = {{a, b, a}, {a, b, b}, {b, b, p}, {a, b, a, a}};
listP = {a, b};

e8[listL, listP]

{{a}, {b}, {a, a}}

User-defined variable names generally start with a lower-case letter to avoid conflict with built-in functions and entities e.g. I, N, C, O, D, E.

Upvotes: 2

Felix Castor
Felix Castor

Reputation: 1675

I changed the elements to strings and it seems to work:

  If[
    ToString[L[[i, j]]] != ToString[P[[j]]], 
    ok = False
    ];

but you can also just write

ok = ToString[L[[i, j]]] != ToString[P[[j]]]

since the result of the != operator is a boolean.

Upvotes: 1

Related Questions