Question: The following function reverses a string. Trace through the function and answer the questions below. def reverse(astring): revStr = [] i = len(astring)-1 while i
The following function reverses a string. Trace through the function and answer the questions below.
def reverse(astring):
revStr = []
i = len(astring)-1
while i >= 0:
revStr.append(astring[i])
i = i - 1
return revStr
print(reverse('quiz 3'))
-
What is the purpose of the loop inside the functions scope and how many iterations does it run for a string of size n? (2 marks)
-
Explain how the append function is used in reversing the string? Can you use the append function to append a character to a string? Why would the string not be reversed if the loop started at 0 and stopped at the last index in the input string astring? (3 marks)
How would you change the code to avoid using append and so that the output is in a string format rather than a list format? What string operators would you use? Whats the order of the steps that you would take to implement a variation of this function? Only explain the steps (you dont have to rewrite the code). (3 marks)
Quiz 3 The following function reverses a string. Trace through the function and answer the questions below. def reverse (astring): revStr = [] i = len (astring) 1 while i >= 0: revStr.append(astring[i]) i = i - 1 return revStr print (reverse ('quiz 3')) 1) What is the purpose of the loop inside the function's scope and how many iterations does it run for a string of size n? (2 marks) 2) Explain how the append function is used in reversing the string? Can you use the append function to append a character to a string? Why would the string not be reversed if the loop started at 0 and stopped at the last index in the input string astring? (3 marks) 3) How would you change the code to avoid using append and so that the output is in a string format rather than a list format? What string operators would you use? What's the order of the steps that you would take to implement a variation of this function? Only explain the steps (you don't have to rewrite the code). (3 marks) | 1.)
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
