Python provides slicing functionality for lists, but for this question, you will
ID: 3799455 • Letter: P
Question
Python provides slicing functionality for lists, but for this question, you will implement your own function capable of producing list slices (you cannot use the slicing operator in your solution). The function should be called slice and take the following three inputs in this specific order: A list, source, which the slice will be created from. This list cannot be modified by your function. A positive integer, start, representing the starting index of the slice you will create. If this value is not in the range [0, Len (list)-1], your function should return an empty list. A positive integer, end, representing the ending index of the slice you will create. If this value is not in the range [start, Len (list)-1], your function should return an empty list. If the parameter values are acceptable, your function will return a list that contains the items from source beginning at the index start and ending at the index end (inclusive). This is different from the Python slice operator, as the item at the index end is also included in the new list. Examples: mylist = ["A", "B". "C", "D", "E", "F", "G", "H", "I", "J"] slice (mylist, 0, 9) should be ["A", "B", "C", "D". "E", "F", "G", "H", "I", "J"] slice(mylist, 3, 4) should be ["D", "E"] slice(mylist, 4, 3) should be [] slice(mylist, 3, 8) should be ["D", "E", T", "G", "H", "I"] slice(mylist, 4, 4) should be ["E"] Save your code is a file called slice.py and add it to your submission zip.Explanation / Answer
Following is the required python code:
def slice( source, start, end ):
length = len(source);
if start >= length:
return [];
if end < start or end >= length:
return [];
#if we reach here, we have acceptable values of start and end
#without using python's slice operator
result = [];
for i in range(start, end+1):
result.append( source[i] );
return result;
#testing
myList = ["A","B","C","D","E","F","G","H","I","J"];
print slice( myList, 0 , 9);
print slice( myList, 3 , 4);
print slice( myList, 4 , 3);
print slice( myList, 3 , 8);
print slice( myList, 4 , 4);
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.