【问题标题】:Determine if Two Strings Are Close确定两个字符串是否接近
【发布时间】:2022-12-03 03:47:20
【问题描述】:

我正在尝试制作一个程序,将 word1 字符串与 word2 字符串进行比较,使其只出现一次

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'))

输入

word1 = 'a',word2 ='aa'

预期的 Output = False

实际的 Output = True

【问题讨论】:

  • 确定两个字符串是否接近的逻辑是什么?你试过debugging吗? What is a debugger and how can it help me diagnose problems?
  • 测试if type(x) is str的意义何在?此时您正在迭代一个字符串列表。 x 怎么可能不是字符串呢?
  • 1.) 通常,您定义一个类是为了创建它的一个实例。您不会那样调用方法。 2.) 为什么在每个字符上调用 x.strip()? 3.) 为什么不简单地计算 word2 中的字符数?

标签: python python-3.x list


【解决方案1】:

你的代码太复杂了。您可以简单地计算每个字符在 word2 中的出现次数:

class Solution:
    def closeStrings(self, word1: str, word2: str) -> bool:
        for x in word1:
            if word2.count(x) > 0: return False
        return True


s = Solution()
print(s.closeStrings(word1='a',word2='aa'))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-21
    • 1970-01-01
    • 2018-09-28
    • 2011-04-25
    • 2022-11-04
    • 2016-05-02
    • 1970-01-01
    • 2016-09-11
    相关资源
    最近更新 更多