【问题标题】:compare 2 strings while using dictionairies (anagrams)在使用字典(字谜)时比较 2 个字符串
【发布时间】:2019-08-22 20:57:35
【问题描述】:

检查两个字符串是否是字谜。编写一个函数 anagrams(s1,s2),给定两个字符串 s1 和 s2,如果它们是,则返回 True 字谜,否则使用字典 False

  1. 如果 len(s1) 与 len(s2) 不同,则它们不是字谜
  2. 我找不到使用字典比较两个字符串的方法。

代码:

D1={}
D2={}

def anagrams(s1,s2):
    if len(s1)!=len(s2):
        return False

    else:
         if D1==D2:
               return True
          else:
                return False

【问题讨论】:

  • 您的字符串是否包含空格?特殊字符呢?我也不明白你为什么需要字典。
  • 请帮助我们和您自己制定a good question。到目前为止,您的帖子中没有任何内容。

标签: python python-3.x dictionary


【解决方案1】:

您可以对每个字符串使用 dict 来计算每个不同字符的出现次数:

def anagrams(s1, s2):
    d = {}
    for s in s1, s2:
        d[s] = {}
        for c in s:
            d[s][c] = d[s].get(c, 0) + 1
    return d[s1] == d[s2]

【讨论】:

    【解决方案2】:

    您可以将单词加载到字典中并比较字典的排序值。

    D1={}
    D2={}
    
    def anagrams(s1,s2):
        if len(s1)!=len(s2):
            return False
    
        else:
            elementNumber = 0
            for char in s1:                    #Load s1 into dictionary
                D1[elementNumber] = char
                elementNumber = elementNumber + 1
    
            elementNumber = 0
            for char in s2:                    #Load s2 into dictionary
                D2[elementNumber] = char
                elementNumber = elementNumber + 1
    
            print(sorted(D1.values()))         #Example output
            print(sorted(D2.values()))         #Example output
    
            if sorted(D1.values())==sorted(D2.values()): #Sort and compare
                 return True
            else:
                 return False
    
    print("Anagrams: "+str(anagrams("Hello", "oHlel"))) #Returns True
    print("Anagrams: "+str(anagrams("Hello", "xyzlo"))) #Returns False
    

    【讨论】:

      【解决方案3】:

      如果你想使用字典,请检查下面的代码

      def anagrams(s1,s2):
          s = s1+s2 #for example s = asd + dsa = asddsa
          l = list(s) #[a,s,d,d,s,a]
          dic = dict(enumerate(l)) # {0: 'a', 1: 's', 2: 'd', 3: 'd', 4: 's', 5: 'a'}
          if len(dic)%2 == 1: #if the two strings are anagrams, the length of the combined strings should be even number
              return False
          else: # now we just compare the two ends of all keys, in the above example, we compare 0 and 5 / 1 and 4 / 2 and 3
              # Notice: the sum of i and the its corresponding party is the len of dic
              i = 0
              while i < len(dic)/2:
                  if dic[i] != dic[len(dic)-1-i]:
                      return False
                      break
      
                  else:
                      i += 1
              return True
      

      或者,您可以使用满足相同目的的 deque 函数。简单的逻辑就是把拖链加在一起,两端比较

      from collections import deque
      def anagrams(s1,s2):
          s = s1+s2 # put them into one string and now we can simply compare if the far left and far right one is the same
          dq = deque(s) # apply deque function to it
          while len(dq) > 1: #if it equals to one
              if dq.popleft() != dq.pop():
                  return False
          if len(dq) == 1:
              return False
          else:
              return True
      

      【讨论】:

        【解决方案4】:

        如果您只是检查一个字谜,请尝试使用 python 的 Counter 对象。只需一行即可。

        来自anagram with Counter

        # Python code to check if two strings are 
        # anagram 
        from collections import Counter 
        
        def anagram(input1, input2): 
        
            # Counter() returns a dictionary data 
            # structure which contains characters  
            # of input as key and their frequencies 
            # as it's corresponding value 
            return Counter(input1) == Counter(input2) 
        
        

        【讨论】:

          猜你喜欢
          • 2020-11-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-11-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多