5 questions for TYL on strings (recursive deletion of substring on string, using slicing)
1. Write
a program for string slicing to check if a string can become empty by recursive
deletion of a substring.
and there's a typo in the assignment shared... recursive deletion of a substring.
use find() to locate the index of the substring them we're going to split it out. Let s = "ararcc"
so 0 1 2 3 4 5
a r a r c c
As you might remember, strings are immutable, so slicing and concatenation is a means of removing this substring from the string.
Remember that when you slice s[m:n], it slices from index m to index n-1. So index n is not inclusive.
Also, if you don't specify m, it slice starts from beginning of the string
if you don't specify n, it slices until end of the string...
Try these out:
>>> s[:5]
'delet'
>>> s[2:]
'letion'
>>> s[2:5]
'let'
>>>
Okay, so now that you're familiar with slicing, the program shouldn't be too difficult.
atpos=2: the starting position of the substring
0 1 2 3 4 5
a r a r c c
so slice till atpos s[:atpos] # will give you "ar"
then go to atpos + length of the substring = 2+3=5 , that would be "c" till the rest of the strign
s[atpos+len(sub):]
Program:
s = "ararcc"
sub="arc"
while True:
if sub in s:
atpos= s.find(sub)
s = s[:atpos]+s[atpos+len(sub):]
else: break
if len(s.strip()):
print("String not empty after recursive deletion:", s)
else:
print("String empty after recursive deletion")
Output:
String empty after recursive deletion
Comments
Post a Comment