Group Abstract Group Abstract

Message Boards Message Boards

0
|
5.1K Views
|
5 Replies
|
3 Total Likes
View groups...
Share
Share this post:

How to subtract a subset from the main list?

Posted 4 years ago

Hi,

list2 is a subset of list1.

list1 = {a, b, c, d, e, c, a};
list2 = {e, c, a};

I would like to have the following output?

{a, b, c, d}
POSTED BY: Alex Teymouri
5 Replies
Posted 4 years ago

Alex:

If there are no repeated items in your lists, then you can use Complement[].

If you have to handle repeated items, as in your first post. Then one way to go about it would be to:

  • Use Tally[] and both lists to get the number of times each item shows up in the list
  • Then you'd walk through the second list (perhaps with Scan[]), and adjust the counts of the first list down based on how many times that item was in the first list.
  • Then you can build a new list with the adjusted tallys

I don't have time to build this function right now. But I hope this helps.

POSTED BY: Mike Besso

Hi Alex,

as far as I understand your question one way would be to do it using strings; the substantial work is done by StringDelete:

string1 = StringJoin[ToString /@ list1];
string2 = StringJoin[ToString /@ list2];
ToExpression@Characters@StringDelete[string1, string2]

Does that meet your requirement? Regards -- Henrik

POSTED BY: Henrik Schachner
Posted 4 years ago

Hi Henrik,

Thank you so much. I used the "Drop" command for deleting a subset of numbers from the main list. Is it correct?

list1 = {6, 3, 8, 11, 20, 6, 14, 3, 0};
list2 = {14, 3, 0};
Drop[list1, -3]
{6, 3, 8, 11, 20, 6}
POSTED BY: Alex Teymouri

Hi Alex,

with Drop[list1, -3] you simply drop the last 3 elements, list2 then is not necessary at all. This is a different task.

POSTED BY: Henrik Schachner
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard