functioncopy-pasteredundancy

How can I change my longest and shortest functions to avoid repeating code in Python?


I'm writing a program in Python to find the shortest and longest strings in an array, eg this is find_shortest

def find_shortest(words):
 
    N = len(words)
    shortest = words[0]
    i = 1
    while i < N:
        if len(shortest) >= len(words[i]): #Change only this line for find_longest
            shortest = words[i]
        i += 1

    return shortest

My problem is that the find_longest function is identical to the find_shortest function, except find_longest uses a <= sign instead of >=. I don't want to copy paste the find_shortest function to make find_longest but I see no alternative. How do I avoid copy pasting and redundancy in this scenario?


Solution

  • You could create a comparison function to use based on what "mode" the function is in

    def find(words, mode):
        compare = (lambda x, y: x >= y) if mode == 'shortest' else (lambda x, y: x <= y)
        N = len(words)
        result = words[0]
        i = 1
        while i < N:
            if compare(len(result), len(words[i])):
                result = words[i]
            i += 1
        
        return result
    

    where mode is the value 'shortest' or 'longest'. Could be simplified to just a boolean if you want. I used a string just for clarity.