【问题标题】:How to write a python program to find the second most repeated word in a given string如何编写 Python 程序来查找给定字符串中重复次数第二多的单词
【发布时间】:2020-06-03 02:50:29
【问题描述】:

我的字符串为 Welcome to Datacurators.tech,我需要找出给定字符串中重复次数第二多的字符。我只需要使用基本的 python 代码(不要使用 import 或 def 函数)。我有下面的代码,但它给了我所有字符的计数。预期输出 (e,c,o,a) 输出可以是任何顺序。

stri = "Welcome to Datacurators.tech"
counts={}
for i in stri:
    counts[i]=stri.count(i)
print (counts)

【问题讨论】:

  • 如果你想计算频率然后,你可以制作直方图或使用Counter(),我猜你不想要后者。
  • 尝试检查if i in counts:。如果是加一个;如果它没有设置为一个。
  • 考虑通过 dict 将字符映射到出现计数,然后简单地使用 pythons sorted() 函数,它不需要任何包含。
  • 接下来是排序并根据asec\desc从排序列表\array中选择适当的1\-2索引。

标签: python jupyter-notebook


【解决方案1】:

你应该使用字典。它遍历字符串。如果它不在dict 中,它会创建一个键-> 值对。如果它已经在dict 中,则它的频率加 1。

map = {}
for eachCharacter in stri:
    if eachCharacter not in map:
        map[eachCharacter] = 1
    else:
        map[eachCharacter] += 1

这为您提供字符串中所有字符的频率(包括空格字符,如果您不需要它,请去掉它)。现在我们按它的值对这个字典进行排序。

newMap = {k: v for k, v in sorted(map.items(), key = lambda item: item[1])}

然后要获得第二频繁,甚至是第 n 最频繁,使用:

list(newMap.keys())[n]

你会得到答案。 希望对您有所帮助!

【讨论】:

  • 注意,list(newMap.keys()) 只能是list(newMap)
  • 我不同意重新发明轮子,是的,这个答案不止一个。至少建议使用defaultdict
【解决方案2】:

按照您的代码,您可以先获取第二个大数字,然后获取计数等于该数字的所有字符:

second_large_count = sorted(set(counts.values()),reverse=True)[1] # 1 means second (large) item

second_large_char_set = {k for k,v in counts.items() if v ==second_large_count}

print(second_large_char_set)

【讨论】:

    【解决方案3】:

    您可以将此块添加到您的代码中:

    second_max = sorted(set(counts.values()))[-2] 
    # the above line fails if the string length is less than 2 or the unique character count is less than 2, so you need to check for that
    seconds = [k for k in counts if counts[k] == second_max] 
    print(seconds) 
    

    另外,请注意,对于stri 中的每个字符,都会调用一个stri.count(),这是O(n)。 所以这意味着你的算法的时间复杂度是 O(n^2) (其中 n 是字符串大小)。

    你可以在 O(nlogn) 中做到这一点:

    stri = "Welcome to Datacurators.tech"
    counts={x:0 for x in stri}
    for i in stri: 
        counts[i] += 1 
    
    # then just add the same block from above.
    

    正如@Pynchia 提到的那样,defaultdictCounter 将是可行的方法,但您不希望导入。

    注意:你可以做得比 O(nlogn) 更好。

    【讨论】:

    • 您应该将计数转换为第一个设置以获得第二个大计数。
    • 不,我不需要这样做。
    • 你的意思是你已经用多个最常见的字符覆盖了这个案例?@Perplexabot
    • 我明白你的意思了。你说的对。谢谢 - 已修复!
    【解决方案4】:
    1. 查找字符频率

    2. 按键对字典进行排序

    3. 然后打印它的倒数第二个值。

    str1 = 'visheshsahu'
    
    dict = {}
    
    for n in str1:
    
            keys = dict.keys()
            if n in keys:
                dict[n] += 1
            else:
                dict[n] = 1
    r = sorted(dict.items(),key=lambda x: x[1])
    
    print(r[-2])
    

    【讨论】:

      猜你喜欢
      • 2012-08-24
      • 2012-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多