【问题标题】:Write an function that takes a string and returns the number of unique characters in the string编写一个函数,它接受一个字符串并返回字符串中唯一字符的数量
【发布时间】:2022-11-15 02:20:36
【问题描述】:

我需要一个使用集合和映射的函数,如何使用集合方法改进这个函数? 该功能有效,但需要修改以导入收集方法。

string = str(input())
check = []
unikal = []
for i in string:
    if i in unikal:
        if not (i in check):
            check.append(i)
            del unikal[unikal.index(i)]
    else:
        if not (i in check):
            unikal.append(i)

print("Number of unique characters: ", len(unikal))

【问题讨论】:

  • 你能解释一下你想让这个函数做什么吗,你只是想找出字符串中唯一字符的数量吗?
  • 仅供参考,没有理由使用str(input()),内置的input() 返回一个字符串,无论用户输入什么。

标签: python python-3.x list methods collections


【解决方案1】:

您可以使用列表方法 count() :

unique = [i for i in input() if string.count(i) == 1]
print(len(unique))

【讨论】:

    【解决方案2】:

    如果您只是想查找字符串中唯一字符的数量,您可以执行以下操作:

    x = "testymctestface"
    len(set(x))
    

    8

    请注意,这会将大写字母视为与小写字母相同的单独字符。

    这是有效的,因为 set 创建了一个唯一输入的集合,例如

    x = "testymctestface"
    set(x)
    

    {'a','c','e','f','m','s','t','y'}


    更新:要缓存评论中提到的结果,您可以使用字典,例如

    input_to_unique_char_count = {}
    
    def get_unique_char_count(x):
        ans = input_to_unique_char_count.get(x)
        if ans is None:
           ans = len(set(x))
           input_to_unique_char_count[x] = ans
        return ans
    
    x1 = input("type input:")
    get_unique_char_count(x1)
    
    get_unique_char_count("testtwo")
    get_unique_char_count("testthree")
    
    # you can see that the dictionary builds up the entries:
    print(input_to_unique_char_count)
    

    类型输入:ysyhsd
    {'ysyhsd': 4, 'testtwo': 5, 'testthree': 5}

    【讨论】:

    • 编写一个应用程序,它接受一个字符串并返回字符串中唯一字符的数量。预计具有相同字符序列的字符串可能会多次传递给该方法。由于计数操作可能很耗时,因此该方法应该缓存结果,这样当给该方法一个先前遇到的字符串时,它会简单地检索存储的结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    • 2022-12-01
    • 1970-01-01
    • 2013-04-18
    • 1970-01-01
    相关资源
    最近更新 更多