I'm trying to write a small program to loop through a list of words and find the numeric order of the letters in the string, e.g. HELLO will return 21345 (I don't want to double up numbers) and PROSPER will be 3527416.
I'm having trouble thinking of a way I can do this. Any ideas? I imagine I'll have to use the ord() function, but that's about as far as I've gotten.

It looks very much like homework. Start with a program to print the letters of each word in alphabetic order.

## All 5 Replies

It looks very much like homework. Start with a program to print the letters of each word in alphabetic order.

It wasn't for homework, it's part of a utility I was writing to solve the hat for headline puzzles. I managed to solve the problem, though it is a little bit unwieldy. I'll post code when I can get back to my desktop

Solution I came up with was:

``````import string, re

word = raw_input("Word to test: ")
letters_list = list(string.ascii_uppercase)
next_val = 1
order = ["" for i in range(100)]

for i in letters_list:
starts = [match.start() for match in re.finditer(re.escape(i), word)]
for j in starts:
order[j] = str(next_val)
next_val += 1

for i in range(len(order)):
if len(order[i]) == 0:
chopped = order[:i]
break

print ''.join(chopped)
``````

Here is my best solution

``````word = raw_input("Word to test: ")
uword = word.upper()

L = sorted((c, pos) for (pos, c) in enumerate(uword))
M = sorted((pos, n) for (n, (c, pos)) in enumerate(L, 1))
result = ''.join(str(n) for (pos, n) in M)

print result
``````

I also have a solution using objects from module collections:

``````from collections import defaultdict, deque

word = raw_input("Word to test: ")
uword = word.upper()

D = defaultdict(deque)
for i, c in enumerate(sorted(uword), 1):
D[c].append(str(i))

L = [D[c].popleft() for c in uword]
result = ''.join(L)

print result
``````

What will you do if the word has more than 9 letters, such as `internationalization` ?

The code works fine for 13 character strings containing multiple occurrences of the same letter, tested with `METAMORPHOSIS` and `BIRTHSTONE`

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.