How DO I write this into Python past assignments I have not been able to copy an
ID: 669411 • Letter: H
Question
How DO I write this into Python past assignments I have not been able to copy and paste code.
In this assignment we will code using a list. Assume, we are given a list of items, and we need to write code for a new function called reverse. (Please note, Python has a built in function to perform this task - we are not using that - we are coding a version of it ourselves).
This function creates another list in which the sequence of all the items is reversed.
Here is the process we will use:
- First, using just a paper and pencil, we will figure out how to do this.
- Next, we will capture this algorithm, from step 1, in pseudo code. Walk thru this to make sure it will work. The pseudo code will be entered as comments at the start of your Python code. (5 points).
- Lastly, we will write the code, and execute it. (10 points) Make sure the code is well annotated with comments (5 points).
- The output should be the two lists and the big-O complexity of your code (if this is done, it is worth an extra 2 points, if it is not done 2 points will be deducted).
Note: Python lists have a built in method called reverse - we will not use this method - instead we are defining our own method.
Explanation / Answer
'''
Pseudo code :
Step 1 : Set s to length of the input array
Step 2 : Create a new list of same size as input list
for each item in input list starting from index 0
Subtract 1 from s
Set newlist[s] to item
Increment the index of item by 1
'''
def reverse(data_list):
length = len(data_list)
s = length
new_list = [None]*length # create a new list of size same as input
for item in data_list: #for each item in the input list
s = s - 1
new_list[s] = item
return new_list
a = [1,2,3,4,5]
print 'original list:'
print a # original list
print 'reversed list:'
print reverse(a) # reversed list list-> [5,4,3,2,1]
print 'big-O complexity:'
print 'O(n)'
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.