【问题标题】:Find number of unique char to be dropped from string to get Anagram using Python使用 Python 查找要从字符串中删除的唯一字符数以获取 Anagram
【发布时间】:2020-05-15 10:00:16
【问题描述】:

Alice 正在学习密码学课程并发现字谜非常有用。如果第一个字符串的字母可以重新排列以形成第二个字符串,我们认为两个字符串是彼此的字谜。换句话说,两个字符串必须包含相同频率的完全相同的字母。例如,bacdc 和 dcbac 是字谜,但 bacdc 和 dcbad 不是。

Alice 决定了一个涉及两个大字符串的加密方案,其中加密取决于使两个字符串变位词所需的最少字符删除数。你能帮她找到这个号码吗?

给定两个字符串,a 和 b,长度可能相同也可能不同,确定生成 a 和 b 字谜所需的最小字符删除数。可以从任一字符串中删除任何字符。

例如,如果 a=cde 和 b=dcf,我们可以从字符串 a 中删除 e,从字符串 b 中删除 f,这样剩下的两个字符串都是 cd 和 dc,它们都是字谜。

我试过的代码。

import math
import os
import random
import re
import sys
from collections import Counter 

# Complete the makeAnagram function below.

def makeAnagram(str1, str2):
   new= str1 + str2
   unique =[]
   z=0
   for char in new[:]:
       a = new.count(char)
       if a%2!=0 and char not in unique:
           z=z+(a%2)
           unique.append(char)
       a=0
   return z
if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    a = input()

    b = input()

    res = makeAnagram(a, b)

    fptr.write(str(res) + '\n')

    fptr.close()

用于输入

fcrxzwscanmligyxyvym

jxwtrhvujlmrpdoqbisbwhmgpmeoke

我的输出是 14

根据给出的答案,输出应该是 30。

【问题讨论】:

  • 在循环底部分配a=0 有什么意义?无论如何,它会立即在循环顶部重新分配。
  • 这个问题有一些奇怪的句子比如For example, if and , we can delete from string and from string so that both remaining strings are and which are anagrams.这是怎么回事?
  • 您的具体问题是什么?你得到什么输出,它是怎么错的?

标签: python string data-structures substring anagram


【解决方案1】:

该功能似乎有效。我不熟悉您写入文件的方式尝试改用它:

fptr = open("MyFile.txt","w")

【讨论】:

    【解决方案2】:

    事实证明,这是两个计数器之间的对称差。直接计算效率更高,但是通过Counter的接口,可以表示为(x - y) + (y - x)

    a = "fcrxzwscanmligyxyvym"
    b = "jxwtrhvujlmrpdoqbisbwhmgpmeoke"
    
    from collections import Counter
    
    x = Counter(a)
    y = Counter(b)
    
    sum(((x - y) + (y - x)).itervalues()) # => 30
    

    为什么 Counter 类没有这个方法,请参阅Why is there no symmetric difference for collections.Counter?

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 2010-11-29
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-10
      • 2019-07-18
      • 1970-01-01
      相关资源
      最近更新 更多