'Codewars execution timeout despite short execution time on other IDEs (Python)

I was solving a problem on CodeWars and my solution keeps getting execution timeouts. I know the code is correct and doesn't take long to execute, since when I plugged the same code and tests into the IDE Atom, it only took 0.117s to execute.

The goal of the task is to create a function for e.g. "is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est".

Is it a problem with CodeWars or is there something I am missing?

Thanks for the help.

def order(sentence):
    new_list =[]
    order = 1
    sentence = sentence.split(' ')
    while len(new_list) < len(sentence):
        for c, x in enumerate(sentence):
            
            try: 
                x.index(str(order))
                print(c)
                order += 1
                new_list.append(sentence[c])
            except:
                continue
    return ' '.join(new_list)


Solution 1:[1]

I think was is happening is that they test an empty string which causes an infinite loop in your code or words without any number. You can try it yourself:

print(order(""))
print(order("this"))

To fix the former, you can use this

if (not sentence.strip())
    return ""

What you might also be looking for is something to sort the list by custom order. Luckily Python provides the sorted method and all you need to do is implement a method that accepts a string and returns an integer.

Please note that I did not handle malign cases of words without any numbers inside, as they are not specified in the exercise.

import re

def find_index(s):
    match = re.search("\d+", s)
    return int(match.group(0))

def order(sentence):
    if (not sentence.strip())
      return ""
    sentence = sentence.split(' ')
    return ' '.join(sorted(sentence, key=lambda x: find_index(x)))

print(order("is2 Thi10s T4est 3a")) # returns "is2 3a T4st Thi10s"

Bonus: this will work also with numbers larger than 9 as demonstrated. Apparently, this is not part of the exercise though.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1