Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort word of a string by number value

Tags:

python

I am trying to solve this problem:

"Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.

Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).

If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers.

Examples: "is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est"

I tried to first split the string that I received and then use the sort() function but I think that is ordering the sentence by the size of each word rather by the number in them.

def order(sentence):
    words = sentence.split()
    words.sort()
    return words

print(order("is2 Thi1s T4est 3a"))

It should order the sentence like this "Thi1s is2 3a T4est" but my code sort the sentence like this ['3a', 'T4est', 'Thi1s', 'is2']

like image 605
Raúl Santamaría Avatar asked Sep 01 '25 15:09

Raúl Santamaría


2 Answers

Function version:

sentence = "is2 Thi1s T4est 3a"

def order(sentence):
    # creates a tuple of (int, word) for each word in the sentence
    # we need a nested listed comprehension to iterate each letter in the word
    # [... for w in sentence.split() ...] -> for each word in the sentence
    # [... for l in w ...] -> for each letter in each word
    # [... if l.isdigit()] -> if the letter is a digit
    # [(int(l), w) ...] -> add a tuple of (int(letter), word) to the final list
    words = [(int(l), w) for w in sentence.split() for l in w if l.isdigit()]
    words.sort(key=lambda t: t[0])
    return " ".join(t[1] for t in words)

print(order(sentence))

>>> Thi1s is2 3a T4est

Here's a fun one-liner

sentence = "is2 Thi1s T4est 3a"
new = " ".join(t[1] for t in sorted([(int(l), w) for w in sentence.split() for l in w if l.isdigit()], key=lambda t: t[0]))
print(new)

>>> Thi1s is2 3a T4est
like image 60
bphi Avatar answered Sep 04 '25 06:09

bphi


I wasn't going to post an answer as this sounds like homework.

That said, there are other answers that aren't as clear/readable. I've kept list expansion out of this example for readability.

def order(sentence):
    words = sentence.split()
    ordered_words = sorted(words, key=int_from_word)
    return " ".join(ordered_words)

def int_from_word(word):
    for character in word:
        if character.isdigit():
            return int(character)
    return None

print(order("is2 Thi1s T4est 3a"))

Output:

Thi1s is2 3a T4est
like image 42
Jim Wright Avatar answered Sep 04 '25 05:09

Jim Wright