7. Reverse


#1

Woohoo! first one in a while i've been able to get without going to the Q&A on this section. I'm definitely going to have to go over this section again, but I feel like my code is just so messy and probably way longer than it needs to be. Can anyone give me some pointers for how to cut down on the code?

Thanks!

def reverse(string):
    lst = []                                #create an empty list
    revlst = []
    string = str(string)                    #make sure the variable is a string
    for i in string:                        #take each letter in the string
        lst.append(i)                       #append to the list
    
    a = len(lst)                            #get length of the list
    for i in string:                        #for each letter in the string
        revlst.append(lst[a-1])             #append in reverse
        a -= 1                              #count backwards to append to newlist
    con_revlst = ''.join([str(mli) for mli in revlst]) 
                                            #join the reversed list into a new list
    return con_revlst
        
print reverse("helpwhoknow!swhatsgoinon")

Also just making sure I can format correctly when posting to Q&A...


#2

@sbburton

There is always room for improvement as always.

Python Example:

def reverse(text):
    return ''.join(letter for letter in list(text)[::-1])

As simple as this!

Any question feel free to ask.


#3

Hah, yes I did see that [::-1], but the problem says not to use that :stuck_out_tongue:


#4

@sbburton

If you want to be picky,

Python Code:

def reverse(text):
    return ''.join(letter for letter in (text[(index + 1) * -1] for index, char in enumerate(text)))

Happy now? It looks more confusing don't it though?


#5

I don't know .

def reverse(text):
if not text == str(text):
return False
else:
while x in range(len(text)) < len(text)-1:
print text[len(text)-1],
del(text[len(text)-1])
else :
print "this is the reverse sentence"

DON'T WORK


#6

very much so...

gimme a minute to figure that out!


#7

This is my own approach:

def reverse (text):
    rev = ""                    # A variable to store the reverse words
    i = len(text)               # Get the string length
    while i > 0:                # while the text is active
  
        rev += text[i-1:i]      #  join the alphabets in reverse
       
        i-=1
    return rev

#8

def reverse(text):
output = ""
for letter in text:
output = letter + output
return output


#9

Whilst far from perfect, I just wanted to share my working approach. One thing I noticed is that the exercise won't let you go through if you try to print the joint result instead of just returning it.

def reverse(text):
    index = len(text) - 1
    result = []
    for char in text:
        result.append(text[index])
        index -= 1
    return "".join(result)
print reverse("Python!")

#10

Or that variant:

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

#11

This seems to be working...

def reverse(text):
l = len(text)
result = ''
print l
while l > 0:
result+=text[l-1]
l -= 1
return str(result)


#12
Yet another possible solution. First one I could get without the Q&A.

def reverse(text):
    ls = []
    rev_ls = []
    for char in text:
        ls.append(char)
    while ls != []:
        rev_ls.append(ls[-1])
        del(ls[-1])
    reverse = "".join(rev_ls)
    return reverse

#13

def reverse(text):
txt_lst = []
r_txt = ""
for i in text:
txt_lst.append(i)
while len(txt_lst) > 0:
r_txt = r_txt + txt_lst.pop()
return r_txt

Apologies if this is redundant, but I didn't see anyone use list.pop()
It seems to work!


#14

We can do this in one statement...

    txt_lst = list(text)

The .pop() method has been demonstrated before, but maybe just not in the new forums (post October 1st). We can use an augmentation operator to assign members to r_txt.

    r_txt += txt_lst.pop()

#15

Thanks for the help; I'm a big fan of concision.


#16

Mine gives me an error. Could somebody help?

Oops, try again. Your code looks a bit off--it threw a "string index out of range" error. Check the Hint if you need help!


#17

I figured it out:
changed l from 0 to 1
and while condition from l


#18

Thanks so much! Very useful!!! I completed mine a very long way - yours is really concise though!!!


#20

Hi , please help to check my code, it always pop part of the chars.

def reverse(text):
str = []
str2 = []
final_str = ''
for char in text:
str.append(char)
print "str is ", str
for i in str:
temp = str.pop()
print "pop is :",temp
str2.append(temp)

print "str2 is ", str2
final_str = ''.join(str2)    
print "final_str is ", final_str
return final_str

The the result is as following:
C:\Python27>python piggame.py
Input string: abcde
str is ['a', 'b', 'c', 'd', 'e']
pop is : e
pop is : d
pop is : c
str2 is ['e', 'd', 'c']
final_str is edc
edc


#21

Who can tell me why after I upload the code then the indent disappears?