Floofk
Floofk

Reputation: 113

Sorting string into identical words

word = "help"
scrambled = ['p','e','h','l']

how would I arranged scrambled to be the same order as word? so pehl into help.

edit 1:

this is for a hangman game, so it would go:
guess 1:
input = "p"
scrambled = ['p']
guess 2:
input = "e"
scrambled = ['p','e']

and so on.

Upvotes: 0

Views: 81

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1122062

list(word) would do it the quickest..

but to sort scrambled you could use:

sorted(scrambled, key=word.index)

or, using in-place sorting:

scrambled.sort(key=word.index)

This works only when word has no repeated letters. For each entry in scrambled, word.index() is called, returning the index of each letter in word, which then are used to sort the scrambled list.

Demo:

>>> word = "help"
>>> scrambled = ['p','e','h','l']
>>> list(word)
['h', 'e', 'l', 'p']
>>> sorted(scrambled, key=word.index)
['h', 'e', 'l', 'p']

For repeated letters, you can build a key function based on the word indices:

def make_sort_key(word):
    indices = {}
    for i, c in enumerate(word):
        indices.setdefault(c, []).append(i)
    def key(c):
        return indices[c].pop()
    return key

sorted(scrambled, key=make_sort_key(word))

This pre-builds indices for each letter in word and returns these as the scrambled list is sorted.

Demo:

>>> word = 'letters'
>>> scrambled = ['s', 'e', 'l', 'r', 'e', 't', 't']
>>> def make_sort_key(word):
...     indices = {}
...     for i, c in enumerate(word):
...         indices.setdefault(c, []).append(i)
...     def key(c):
...         return indices[c].pop()
...     return key
... 
>>> sorted(scrambled, key=make_sort_key(word))
['l', 'e', 't', 't', 'e', 'r', 's']

Upvotes: 2

Andrew Clark
Andrew Clark

Reputation: 208475

Here is a solution that works with repeated letters:

def make_key(word):
    prev = {}
    def key(c):
        prev[c] = word.index(c, prev.get(c, -1) + 1)
        return prev[c]
    return key

For example:

>>> word = 'lollipop'
>>> scrambled = ['o', 'i', 'l', 'l', 'p', 'p', 'o', 'l']
>>> scrambled.sort(key=make_key(word))
>>> scrambled
['l', 'o', 'l', 'l', 'i', 'p', 'o', 'p']

Upvotes: 0

Aaron Hall
Aaron Hall

Reputation: 395075

I interpreted this literally:

>>> word = "help"
>>> scrambled = ['p','e','h','l', 'p','e','h','l', ]
>>> scrambled.sort(key=word.find)
>>> scrambled
['h', 'h', 'e', 'e', 'l', 'l', 'p', 'p']

Upvotes: 0

Related Questions