In: Computer Science
Python. Tuples and strings can also be sliced and concatenated.
Let x = ['F','l','o','r','i','d','a']. How does cotDel(x, 3) compare to del x[3]?
Let y = ('F','l','o','r','i','d','a'). How does cotDel(y, 3) compare to del y[3]?
Let z = 'Florida'. How does cotDel(z, 3) compare to del z[3]?
Give an explanation about what you observed. This question refers to the following statement.
Define function cotDel(s,i) that deletes the ith item of list s, s[i]. In other words this function should do what the statement del s[i] does. Your function should use slicing and concatenation. Test your function with the list x of problem 1, deleting x[2]. Furthermore, your code should be written so that your program can be imported by other programs to make the function cotDel(s,i) available to them.
Hi,
Hope you are doing fine. I have coded the above question in python keeping all the conditions in mind. Now, have a look at the code of cotDel(s,i) first and then have a look at other explanations. The code snippets have also been attached to get a clear picture regarding indentation. The code has been clearly explained using comments that have been highlighted in bold.
Program:
def cotDel(s,i):
#if i is the index of the last element
then
if i==len(s)-1:
#we slice the list s upto i and store in
new
new=s[:i]
#new is returned
return new
#if i is between 0 and less than length of list s
then,
elif i>=0 and i<len(s):
#we slice s from start to i, and from i+1 to
end and concatenate them to store in new
new=s[:i]+s[i+1:]
#return new
return new
#if i is an invalid index
else:
print("Invalid index")
Code snippet from editor:
Test file code:
from cotDel import cotDel
#declaring a list,tuple and a string
x = ['F','l','o','r','i','d','a']
y = ('F','l','o','r','i','d','a')
z = 'Florida'
#using cotDel
x=cotDel(x,3)
y=cotDel(y,3)
z=cotDel(z,3)
#printing results
print(x)
print(y)
print(z)
Code snippet:
Output:
Also, as asked in the question we test using only list x by deleting x[2] using cotDel.
Code:
from cotDel import cotDel
#declaring a list,tuple and a string
x = ['F','l','o','r','i','d','a']
print("Before deleting: ",x)
#calling cotDel
x=cotDel(x,2)
print("After deleting: ",x)
Code snippet:
Output:
As for the questions asked:
Explaining this using code in jupyter notebook as it is visually more clear to understand errors and there is line by line output:
The above errors for y and z occur because del is only supported for list items and not string or tuples.