i am trying to make a program that compares word1 strings with word2 string to occur only once
class Solution:
def closeStrings(self, word1: str, word2: str) -> bool:
word1 = [x.strip() for x in word1]
word2 = [x.strip() for x in word2]
update = False
for x in word1:
if(x in word2):
update = True
if(type(x) is str):
a = word1.index(x)
b = word2.index(x)
word1[a]=''
word2[b]=''
else:
update = False
else:
update = False
break
return update
print(Solution.closeStrings(Solution,word1='a',word2='aa'))
Input
word1 = 'a',word2 ='aa'
Expected
Output = False
Actual
Output = True
CodePudding user response:
print(Solution.closeStrings(Solution,word1='a',word2='aa'))
You create a class in order to be able to create an instance of it. That way you don't need to pass
Solution
as theself
parameter.word1 = [x.strip() for x in word1]
It looks like you expect to remove spaces. But you'll get a list of strings with empty strings for the spaces. That's not what you want. See the output of
print([x.strip() for x in "Hello world"])
Your algorithm is way too complicated.
You can simply count the occurrences of each character in word2:
class Solution:
def closeStrings(self, word1: str, word2: str) -> bool:
for x in word1:
if word2.count(x) != word1.count(x): return False
return True
s = Solution()
print(s.closeStrings(word1='a',word2='aa'))
print(s.closeStrings(word1='abcb',word2='bcab'))
CodePudding user response:
Extending to other more solution answer by @Thomas Weller well explained by him
class Solution:
def closeStrings(self, word1: str, word2: str) -> bool:
for i in word1:
if i not in word2:
return False
for i in word2:
if i not in word1:
return False
return True
def closeStrings2(self, word1: str, word2: str) -> bool:
if len(word1) != len(word2):
return False
if set(word1) != set(word2):
return False
return True
def closeStrings3(self, word1: str, word2: str) -> bool:
if len(word1) != len(word2):
return False
if sorted(word1) != sorted(word2):
return False
return True
print(Solution().closeStrings(word1="cabbba", word2="abbccc"))
print(Solution().closeStrings3(word1="cabbba", word2="aabbss"))
print(Solution().closeStrings3(word1="cabbba", word2="aabbss"))