In: Computer Science
Using Python:
"We have a list of strings: \n",
"```python\n",
"CharList = ['a', 'b', 'c', 'd']\n",
"```\n",
"Now, we write a program to delete some elements
from the list. <br> \n",
"The indexes of the elements to be deleted are
stored in IndexList <br>\n",
"\n",
"```Scenario-1```: IndexList = [3, 0]\n",
"```python\n",
"CharList = ['a', 'b', 'c', 'd']\n",
"IndexList = [3, 0]\n",
"for n in range(0,
len(IndexList)): \n",
" index=IndexList[n]\n",
" print(index)\n",
"
print(CharList[index])\n",
" del
CharList[index]\n",
"```\n",
"The code under Scenario-1 works well: 'a' and
'd' are deleted <br>\n",
"<br>\n",
"```Scenario-2```: IndexList = [0, 3]\n",
"```python\n",
"CharList = ['a', 'b', 'c', 'd']\n",
"IndexList = [0, 3]\n",
"for n in range(0,
len(IndexList)): \n",
" index=IndexList[n]\n",
" print(index)\n",
"
print(CharList[index])\n",
" del
CharList[index]\n",
"```\n",
"The code under Scenario-2 does not work: You
will see \"IndexError: list index out of range\"
<br>\n",
"<br>\n",
"Write a function in which the elements can be
deleted from the list <br>\n",
"It must be a general solution.
<br>\n",
"CharList contains strings, not other stuff
<br>\n",
"IndexList contains integers, not other stuff
<br>\n",
"```python\n",
"def Answer18(CharList, IndexList)\n",
" # parameters:\n",
" #
CharList is a list of strings\n",
" #
IndexList is a list of integers, and it can be [2, 3, 1], [1, 3,
2], etc\n",
" # return: None\n",
" # If the index of an element
of CharList is in IndexList, \n",
" # then the element will be
deleted from CharList.\n",
"```"
"""''''''"""
"""The idea behind the code is that, after every deletion from the CharList, list size decreases by one.
To overcome the problem of indices always remain in the range, we have to subtract 1 from all the indices which are greater than
current index, so that the indices never get out of the range."""
def Answer18(CharList, IndexList): #function definition
for n in range(0, len(IndexList)): #looping through index list
index=IndexList[n]
print(index) #printing index
print(CharList[index]) #printing character to be deleted
del CharList[index] #deleting character
'''here we subtract 1 from each index greater than current index'''
for i in range(0, len(IndexList)): #looping through index list
if index < IndexList[i]: #checking if current index is smaller than index in the list
IndexList[i] = IndexList[i] - 1 #subtracting 1
return CharList #returning the remaining character list
CharList = ['a', 'b', 'c', 'd'] #sample testcase
IndexList = [0, 3]
print('Character List after deletion: ', Answer18(CharList, IndexList))
Screenshot of code:
Screenshot of output: