lundi 7 septembre 2015

Return lexicographically earliest string in Python

Write a function called answer(chunk, word) that returns the shortest, lexicographically earliest string that can be formed by removing occurrences of word from chunk.

Inputs:
    (string) chunk = "lololololo"
    (string) word = "lol"
Output:
    (string) "looo"

Inputs:
    (string) chunk = "goodgooogoogfogoood"
    (string) word = "goo"
Output:
    (string) "dogfood"

My below program is able to clear all the test cases except one and I am not able to figure out where I am going wrong.

def answer(chunk, word):

    shortestWord = []

    shortestWord.append("".join(chunk.split(word)))

    shortestWord.append("".join(chunk.rsplit(word)))

    if len(shortestWord) >= 1:

        return sorted(shortestWord)[0]

    else:
        return None

Could anyone help me to figure out or give some idea where I might be wrong. Thanks

Aucun commentaire:

Enregistrer un commentaire