2

I am trying to compare the two strings: 'apple' and 'pear' and return letters that do not belong to the other string.

For example, 'apple' does not contain 'r' in 'pear'

'pear' does not contain 'l' and 'p' in apple (pear contains p but does not contains two p's).

So I want to have a function that returns 'r', 'l', and 'p'.

I tried set, but it ignores the duplicates (p, in this example).

def solution(A, B):
    N = len(A)
    M = len(B)
    letters_not_in_B = list(set([c for c in A if c not in B]))
    letters_not_in_A = list(set([c for c in B if c not in A]))
    answer = len(letters_not_in_B) + len(letters_not_in_A)
    return answer
4
  • 1
    Can you post the code that you have tried? Commented Jan 5, 2018 at 19:14
  • chris. I just did. Commented Jan 5, 2018 at 19:15
  • 1
    If you want duplicates, than you shouldn't use sets since they only have unique values, just use lists Commented Jan 5, 2018 at 19:17
  • 1
    You say you want the function to return 'r', 'l', and 'p' but your attempt, after having letters, instead returns a number. Make up your mind? Commented Jan 5, 2018 at 19:28

3 Answers 3

6

You can compare the character counts for each separate string resulting from the concatenation of the parameters a and b:

def get_results(a, b):
  return list(set([i for i in a+b if a.count(i) != b.count(i)]))

print(get_results('apple', 'pear'))

Output:

['p', 'r', 'l']
Sign up to request clarification or add additional context in comments.

3 Comments

This returns identical results for get_results('apppppple', 'pear'), which is incorrect.
@JohnGordon the OP wants data formatted with no duplicates where there occurs a letter that does not have equal counts in each string.
I interpret "return letters that do not belong to the other string" as meaning "If the first string has one p and the second string has five ps, I want four ps returned." Shame on OP for not being precise, I suppose.
5

Use a Counter

from collections import Counter
Counter('apple') - Counter('pear') # --> Counter({'p': 1, 'l': 1})
Counter('pear') - Counter('apple') # --> Counter({'r': 1})

Comments

-1
def solution(a, b):

    # create mutable list copies of a and b
    list_a = list(a)
    list_b = list(b)

    for ch in a:
        if ch in list_b:
            list_b.remove(ch)

    for ch in b:
        if ch in list_a:
            list_a.remove(ch)

    return list_a + list_b

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.