Reputation: 13
So the assignment I was given was to create a function that takes x as an argument which assigns numbers according to (what I assume to be) the inputted letter's ordinal values. Keep in mind that only non-repeating lowercase letters are to be inputted.
Since "a < b", and "a < c", if I were to input a string "abc" into this function, it should return '123'. If I inputted "zad", it should return "312". In other words, smallest letter starts at 1, the next smallest, 2, etc.
How should I go about construction a function that fits this criteria? I figured I would include a range going from ord[a] to ord [z] and then include an elif loop statement. Any pointers?
Upvotes: 0
Views: 76
Reputation: 4035
str1 = "bca"
print (sorted([str1.index(x)+1 for x in sorted(str1)]))
Sort them first and print sorted index of them. Carefull, +1 to index, because index starting from 0
.
Upvotes: 0
Reputation: 10565
You can construct a dictionary that maps each character to its position in the sorted list of the distinct characters in the original string:
def perm(s):
indexes = {x:i+1 for i,x in enumerate(sorted(set(s)))}
return ''.join(str(indexes[x]) for x in s)
print(perm('abc'))
print(perm('zad'))
Upvotes: 2