Home » programming » Messing around: Message to indexes in Python

Messing around: Message to indexes in Python

This post is inspired by a comment in Google+ by Gianluca Romanin. The conversation was on a thread by Guido van Rossum. If anyone knows how to share a link please, tell me.

The implemented function returns a string with all the different characters of the message sorted and the necessary indexes to reproduce the initial message.

message = 'I miss you'

def convert(message):
    """ Convert messages up to 10 different characters """
    characters = sorted(list(set(message)))
    converted = ''
    seen = dict()
    for c in message:
        try:
            index = seen[c]
        except KeyError:
            seen[c] = characters.index(c)
            index = seen[c]
        converted = ''.join([converted, str(index)])

    return ''.join(characters), converted

characters, converted = convert(message)
print("Please try using Python 3...")
print(''.join(["alphabet = '", characters, "'"]))
print(''.join(["numbers = '", converted, "'"]))
print('for i in range(len(numbers)):\n\tprint(alphabet[int(numbers[i])], end="")')
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: