7/15 reverse


#1

Not sure if i am missing something or if i am doing something wrong. Some help would be apreciated.

CODE:

def reverse(text):
    string = []
    reverse_string = []
    for i in text:
      string.append(i)
      ans = ''.join(string)
      count = len(ans)
      while count > 0:
        reverse_string.append(ans[count - 1])
        count = count - 1
        rev_ans = ''.join(reverse_string)
    
  print ans
  print reverse_string
  print rev_ans

RESULTS:

abc
[‘a’, ‘b’, ‘a’, ‘c’, ‘b’, ‘a’]
abacba

Python!
[‘P’, ‘y’, ‘P’, ‘t’, ‘y’, ‘P’, ‘h’, ‘t’, ‘y’, ‘P’, ‘o’, ‘h’, ‘t’, ‘y’, ‘P’, ‘n’, ‘o’, ‘h’, ‘t’, ‘y’, ‘P’, ‘!’, ‘n’, ‘o’, ‘h’, ‘t’, ‘y’, ‘P’]
PyPtyPhtyPohtyPnohtyP!nohtyP


#2

you nested your while loop inside your for loop, this means your while loop will run several times. That can’t be right?


#3

I missed that :joy: Thank you very much for pointing that out, nesting the while loop under the function solved my problem.

def reverse(text):
	  string = []
	  reverse_string = []
	  for i in text:
		  string.append(i)
		  ans = ''.join(string)
		  count = len(ans)
	  while count > 0:
		  reverse_string.append(ans[count - 1])
		  count = count - 1
		  rev_ans = ''.join(reverse_string)
  	  return rev_ans
	  print ans
	  print reverse_string
	  print rev_ans

#4

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