【问题标题】:Is there a Python function that counts all the items in a word, in one go?是否有一个 Python 函数可以一次性计算一个单词中的所有项目?
【发布时间】:2019-02-13 05:49:58
【问题描述】:

我正在尝试将一个字符串编码为一个新字符串,如果字符仅出现一次(在原始字符串中),则使用 '(' 和 ')' 字符出现多次(在原始字符串中)。我的问题是当我遍历字符串时,有时重复的字符只计为 1。我肯定走错了路。

我尝试做的是用 if else 语句做一个嵌套的 for 循环,我将在下面提供我的代码。

def duplicate_encode(word):
    replace = [')' if word.count(i) > 1 else '(' for i in word]
    strreplace = ''.join(replace)
    print(strreplace)

a = input("Insert string here: ")
duplicate_encode(a)

最值得注意的例子是字符串“Success”。结果应该是')())())',而我得到的是'(())())'。我还尝试了另一种方式,在计算字母时使用内部打印,第一个“S”始终计为 1,而后两个“s”计为 2。

【问题讨论】:

  • 大小写不是同一个字符。
  • 嗯,好吧,那我试试看,马上回来。
  • 好的,解决了,谢谢。
  • 注意:每个字母iword.count(i) 效率不是很高O(n^2)。您可以查看collections.Counter()O(n) 中执行此操作。
  • 请注意,有些语言没有大小写,而有些语言则不一定每个字母都in。德语曾经是这方面的一个例子:单词 straße 表示 street,但大写拼写为 STRASSE,因为没有大写 ß。 There is now, since 2008 (Unicode) and 2017 (officialdom).

标签: python python-3.x algorithm


【解决方案1】:

如果您希望字符不区分大小写,请在循环之前将输入字符串转换为一种情况。

def duplicate_encode(word):
    word = word.lower()
    replace = [')' if word.count(i) > 1 else '(' for i in word]
    strreplace = ''.join(replace)
    print(strreplace)

【讨论】:

    猜你喜欢
    • 2023-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多