Organize string based on numbers

Asked

Viewed 318 times

2

I am learning to program in Python and for this I make challenges that I find on the internet in order to better fix each method, function etc This challenge consists of creating a function that sorts a string in which each word has a number of 1-9 in the middle according to the number contained without removing it from the string.

Ex: "Ess1a 4vida 3a 2é re5al" após a função "Ess1a 2é 3a 4vida re5al"

The code is as follows::

    def order(sentence):
        new_sent = []
        for word in sentence.split():
            char = list(word)
                for c in char:
                    if c in str(range(1, 10)):
                        new_sent.insert(int(c)-1, word)  
        return " ".join(new_sent)   

When testing the code it worked to "is2 Thi1s T4est 3a" but it didn’t work para 'Fo1r the2 4of g3ood pe6ople th5e' .

I can’t find the problem in the code.

1 answer

1

The problem with your code is basically that you insert values in the list into positions that do not yet exist

>>> my_list = []
>>> my_list.insert(5, 'foo')
>>> my_list.insert(4, 'bar')
>>> my_list
['foo', 'bar']

Your first test worked in the order in which the text was inserted

>>> my_list = []
>>> my_list.insert(1, 'is2')
>>> my_list.insert(0, 'Thi1s')
>>> my_list.insert(3, 'T4est')
>>> my_list.insert(2, '3a')
>>> my_list
['Thi1s', 'is2', '3a', 'T4est']

Any different order could give an unexpected result. There is a simpler way to do this, just use the builtin function Sorted:

def order_key(word):
    for char in word:
        if char.isdigit():
            return char


print(sorted('Ess1a 4vida 3a 2é re5al'.split(), key=order_key))

The parameter key of function sorted determines what will be the organization criterion of the list, in which case I created a function that returns the number inside the word.

Another detail, take care of that stretch str(range(1, 10) in python2 the result would be:

>>> str(range(1, 10))
'[1, 2, 3, 4, 5, 6, 7, 8, 9]'

Already in python3

>>> str(range(1, 10))
'range(1, 10)'

I believe that’s not what you were looking for, maybe it was:

>>> map(str, range(1, 10))
['1', '2', '3', '4', '5', '6', '7', '8', '9']

The buitin function map apply a certain function to all items of an iterable. Just be careful because in python3 the map function returns a generator.

  • Thank you! I was in doubt if inserting values in a position that was still non-existent was the problem. But the question remains: what made the code correctly order the first test but not the second? I will take this hint of the map in another code that was also giving problem, probably this was the problem.

  • I edited the answer added the explanation of why the first test worked, from a look. If it has helped, please indicate the answer as the chosen one and/or an up in it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.