Reputation:
I want to instruct the computer so that if a character in string 'a' is also a character in string 'b', to remove that character (just that one character), however what the code below is doing is removing all of the same characters from the string at one go. Any help?
I have tried to use a[I] and b[I] to replace the index for each loop, but then the code below needs to be changed entirely, because I can no longer do 'for I in a' and 'if I in b', as I need integer references for the 'i's.
e.g. a = "askhfidshf" b = "fhsdhfojej"
def permutation_checker(a,b):
if a==b:
print("a is a permutation of b")
if a != b:
while a and b:
for i in a:
if i in b:
new_a = a.replace(i,"")
print(new_a)
a = new_a
new_b = b.replace(i,"")
print(new_b)
b =new_b
if (a=="") and b == "":
print("a is a permutation of b")
Upvotes: 0
Views: 26
Reputation: 588
I'd consider string manipulation a little complicated to do with so, I would recommend converting it into an array because you can utilize the index method and your challenge for getting an integer reference will be solved. Take a look at the code I came up with.
def permutation_checker(a, b):
array_a = [i for i in a] # converting the string to an array
array_b = [i for i in b] # converting the string to an array
for i in range(len(array_a )):
if array_a[i] in array_b:
char_index = array_b.index(array_a[i]) # getting the first index of the value array_a[i] within array_b
array_b[char_index] = ''
if array_b == [''] * len(b):
print(f'{a} is a permutation of {b}')
Upvotes: 0
Reputation: 59459
The replace
method takes a parameter which specifies how many occurrences shall be replaced. By default it will replace all.
str.replace(old, new[, count])
Upvotes: 1