Reputation: 127
Given that certain characters are 'abcdef' = char I would like to 1) remove 3rd char of the 3 chars in a row in a word, and 2) from changed word, remove 2nd char of the 2 chars in a row in the word.
E.g. If there is a word 'bacifeaghab' it should
1) first remove 'c' and 'a', which is ba(c)ife(a)hab and change word into 'baifehab'
2) remove 'a','e', and 'b', which is b(a)if(e)ha(b) and change word into 'bifha'
This is what I have done so far, but when I run this and put word in it, it doesn't pint anything. Not even error or blank(' '), it just goes to next line without '>>>'.
def removal(w):
x,y = 0,0
while y < len(w)-2:
if (w[y] and w[y+1] and w[y+2]) in 'abcdef':
w = w[:y+2] + w[y+3:]
while x < len(w):
if w[x] in 'abcedf':
w = w[:x+1] + w[x+2:]
x = x+1
else :
x = x+1
return(w)
Could anyone find out what's wrong??
Since it was first time for me to use while loop, I thought that using double while loop can be a problem, so also tried,
def removal(w):
x,y,z = 0,0,0
while y < len(w)-2:
if (w[y] and w[y+1] and w[y+2]) in 'abcdef':
w = w[:y+2] + w[y+3:]
return(w)
But same result. I also tried print(w) at the end of function. same result.
Upvotes: 1
Views: 1050
Reputation: 20424
There were 2
errors that I have corrected in your code. The first being that you weren't incrementing x
properly (as you did not need the elif
) and you had forgotten completely to increment y
!
I corrected these and then also, in your if
conditions, your syntax was incorrect. The part in the brackets evaluated to the last element and then just this was checked to see if it was in the string 'abcdef'
. I have corrected that now to check each individual element in turn.
So now the function is:
def removal(w):
chars = 'abcdef'
x,y = 0,0
while y < len(w)-2:
if w[y] in chars and w[y+1] in chars and w[y+2] in chars:
w = w[:y+2] + w[y+3:]
y += 3
while x < len(w):
if w[x] in 'abcedf' and w[x+1] in 'abcdef':
w = w[:x+1] + w[x+2:]
x += 2
return w
and calling it with 'bacifeahab'
(without the 'g'
which I think was a typo in your e.g.):
removal("bacifeahab")
returns
what you wanted:
'bifha'
Hope this helps!
Upvotes: 2