Software Engineering

Find the Maximum Length Difference between Lists/Arrays in Python

The challenge

You are given two arrays a1 and a2 of strings. Each string is composed of letters from a to z. Let x be any string in the first array and y be any string in the second array.

Find max(abs(length(x) − length(y)))

If a1 and/or a2 are empty return -1 in each language except in Haskell (F#) where you will return Nothing (None).


a1 = ["hoqq", "bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"]
a2 = ["cccooommaaqqoxii", "gggqaffhhh", "tttoowwwmmww"]
mxdiflg(a1, a2) --> 13

The solution in Python

Option 1:

def mxdiflg(a1, a2):
    if a1 and a2:
        return max(
            len(max(a1, key=len)) - len(min(a2, key=len)),
            len(max(a2, key=len)) - len(min(a1, key=len)))
    return -1

Option 2:

def mxdiflg(a1, a2):
    if a1 and a2:
        return max(abs(len(x) - len(y)) for x in a1 for y in a2)
    return -1

Option 3:

def mxdiflg(a1, a2):
    if not a1 or not a2: return -1
    max_a1 = max([len(x) for x in a1])
    min_a1 = min([len(x) for x in a1])
    max_a2 = max([len(x) for x in a2])
    min_a2 = min([len(x) for x in a2])
    return max(max_a1 - min_a2, max_a2 - min_a1)

Test cases to validate our solution

test.describe("mxdiflg")"Basic tests")
s1 = ["hoqq", "bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"]
s2 = ["cccooommaaqqoxii", "gggqaffhhh", "tttoowwwmmww"]
test.assert_equals(mxdiflg(s1, s2), 13)
s1 = ["ejjjjmmtthh", "zxxuueeg", "aanlljrrrxx", "dqqqaaabbb", "oocccffuucccjjjkkkjyyyeehh"]
s2 = ["bbbaaayddqbbrrrv"]
test.assert_equals(mxdiflg(s1, s2), 10)
s1 = ["ccct", "tkkeeeyy", "ggiikffsszzoo", "nnngssddu", "rrllccqqqqwuuurdd", "kkbbddaakkk"]
s2 = ["tttxxxxxxgiiyyy", "ooorcvvj", "yzzzhhhfffaaavvvpp", "jjvvvqqllgaaannn", "tttooo", "qmmzzbhhbb"]
test.assert_equals(mxdiflg(s1, s2), 14) 
s1 = []
s2 = ["cccooommaaqqoxii", "gggqaffhhh", "tttoowwwmmww"]
test.assert_equals(mxdiflg(s1, s2), -1) 
s2 = []
s1 = ["cccooommaaqqoxii", "gggqaffhhh", "tttoowwwmmww"]
test.assert_equals(mxdiflg(s1, s2), -1) 
s1 = []
s2 = []
test.assert_equals(mxdiflg(s1, s2), -1) 

from random import randint

def mxdiflgSol(a1, a2):
    mx = -1
    for x in a1:
        for y in a2:
            diff = abs(len(x) - len(y))
            if (diff > mx):
                mx = diff
    return mx

def do_ex(k):
    a1, i = [], 0
    while (i < k):
        res, j = "", 0
        while (j < randint(1, 20)):
            res += chr(randint(97, 122)) * randint(1, 3)
            j += 1
        i += 1
    return a1

def randomTests():
    print("100 Random tests ****************** ")
    for _ in range(0, 100):
        s1 = do_ex(randint(0, 10))
        s2 = do_ex(randint(0, 8))
        test.assert_equals(mxdiflg(s1, s2), mxdiflgSol(s1, s2))