Mix strings and take away duplicates in Python


The problem

Take 2 strings s1 and s2 together with solely letters from ato z. Return a brand new sorted string, the longest attainable, containing distinct letters – every taken solely as soon as – coming from s1 or s2.


a = "xyaabbbccccdefww"
b = "xxxxyyyyabklmopq"
longest(a, b) -> "abcdefklmopqwxy"

a = "abcdefghijklmnopqrstuvwxyz"
longest(a, a) -> "abcdefghijklmnopqrstuvwxyz"

The answer in Python code

Choice 1 (Utilizing a Dictionary):

def longest(a1, a2):
    a3 = listing(dict.fromkeys(sorted(a1+a2)))
    return "".be part of(a3)

Choice 2 (Utilizing a Set):

def longest(a1, a2):
    return "".be part of(sorted(set(a1 + a2)))

Choice 3 (Utilizing a Union):

def longest(s1, s2):
    return ''.be part of(sorted(set(s1).union(s2)))

Take a look at circumstances to validate our answer

import take a look at as take a look at
@take a look at.describe("longest")
def assessments():
    @take a look at.it("fundamental assessments")
    def fundamentals():
        take a look at.assert_equals(longest("aretheyhere", "yestheyarehere"), "aehrsty")
        take a look at.assert_equals(longest("loopingisfunbutdangerous", "lessdangerousthancoding"), "abcdefghilnoprstu")
        take a look at.assert_equals(longest("inmanylanguages", "theresapairoffunctions"), "acefghilmnoprstuy")


Leave a Reply