Sunday, April 14, 2024
HomeSoftware EngineeringMix strings and take away duplicates in Python

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 potential, 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 = record(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)))

Check instances to validate our resolution

import take a look at as take a look at
@take a look at.describe("longest")
def exams():
    @take a look"fundamental exams")
    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")


Please enter your comment!
Please enter your name here

Most Popular

Recent Comments