James Adams
James Adams

Reputation: 23

Python remove same characters from a list

Basically, I want to remove the characters from two strings, as many times as they occur in both. For example if we got two strings "cat","cats", when I print the final result I would have "s". What have I done is the following: I have a function which takes two strings and converts them into two separate lists, which are sorted straight after that. I've got a loop which checks whether the first part of the string is in the second one and then it removes the occurrence, however the problem is that if I use the strings "cat","cast" I would get "st" instead of just "s". I know where the problem is exactly in my code. I believe I have to loop through both of the lists but I can't find a solution.I am using python 3 Thank you for taking your time.

def func1(arg1,arg2)
  l1=list(arg1)
  l1.sort()
  l2=list(arg2)
  l2.sort()
    for i in l1:
    if (l1[0]==l2[0]):
            del l2[0]

Upvotes: 2

Views: 1402

Answers (3)

sytech
sytech

Reputation: 40861

The problem with the code you've written is that it depends on the position in the string. You're checking if the character at a given index in arg1 is the same as the character in the same position in arg2. You want to check for all occurrences of the character, regardless of position. A way of writing that solution independent of position might be

def foo(arg1, arg2):
    new_string = arg2
    for char in set(arg1):
        new_string = new_string.replace(char, "")
    for char in set(arg2):
        new_string = new_string.replace(char, "")
    return new_string

Depending on the desired result, can use the symmetric difference of the sets for each string. That would be elements in either arg1 or arg2, but not both.

>>> set("cat") ^ set("cast")
{"s"}
>>> set("hello") ^ set("world")
{'d', 'e', 'h', 'w', 'r'}

Or if you want the regular difference, use difference between arg2 and arg1. That would be elements in arg2, excluding elements in arg1.

>>> set("cast") - set("cat")
{'s'}
>>> set("world") - set("hello")
{'r', 'd', 'w'}

Upvotes: 0

corn3lius
corn3lius

Reputation: 4985

this will check all the values of the shorter string and remove duplicates or adding missing values returning the differences of them .

I believe the set approach wouldn't catch "catt" ^ "cats" = ['t','s']

def func1(arg1,arg2):

    l1, l2 = list(arg1), list(arg2)
    if len(l1) > len(l2):
        l2,l1 = l1,l2
    while l1: 
        val= l1.pop()
        if l2.count(val) > 0:
            l2.remove(val)
        else:
            l2.extend(val)
    return l2

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78546

You can convert each of the strings to sets and take their symmetric_difference:

def func1(arg1, arg2):
    diff = set(arg1).symmetric_difference(arg2)
    return ''.join(sorted(diff))

>>> func1('cat', 'cast')
's'

Upvotes: 1

Related Questions