Reverse: solution with dictionary


I flicked through the forums for this exercise and couldn't find any other solutions that utilised a dictionary.
I thought it was a pretty concise solution.

def reverse(word):
    s1 = {}
    for index, l in enumerate(word):
        s1[len(word)-1-index] = l
    s2 = ""
    for key in sorted(s1):
        s2 += str(s1[key])
    return s2


I think you can simplify this code :slight_smile:

def reverse(text):
    rev = ''
    count = len(text)
    while count > 0:
        rev += text[count - 1]
        count -= 1
    return rev

I assigned variable 'rev' to an empty string. Count Is obvious. While count is greater than 0, reverse plus count -1 equals itself. Then rev is returned.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.