zoukankan      html  css  js  c++  java
  • 【Kata Daily 190917】Numericals of a String(字符出现的次数)

    题目:

    You are given an input string.

    For each symbol in the string if it's the first character occurence, replace it with a '1', else replace it with the amount of times you've already seen it...

    But will your code be performant enough?


    Examples:

    input   =  "Hello, World!"
    result  =  "1112111121311"
    
    input   =  "aaaaaaaaaaaa"
    result  =  "123456789101112"

    题目大意:将字符出现的次数打印出来,以数字1,2,3,,,表示

    解题办法:(再想想,也许就出来了)

    def numericals(s):
        # code
        dic = {}
        L = []
        for i in s:
            if i not in dic.keys():
                dic[i] = 1
                L.append(dic[i])
            else:
                dic[i] += 1
                L.append(dic[i])
        return ''.join([str(x) for x in L])

    用时:1小时3分51秒,,,真长。。。

    看下别人的解法:

    1、使用defaultdict

    from collections import defaultdict
    
    def numericals(s):
        d, lst = defaultdict(int), []
        for c in s:
            d[c] += 1
            lst.append(d[c])
        return ''.join(map(str, lst))

    2、使用生成器

    from collections import Counter
    
    def numericals(s):
        def f(s):
            cnts = Counter()
            for c in s:
                cnts[c] += 1
                yield cnts[c]
        return ''.join(map(str, f(s)))

    知识点:

    1、使用计数count

    2、字典可以使用特殊字符作为key

    3、将一个list转化为str:

      3.1、如果list中有数值,需要转为str,可以使用遍历:

    str(x) for x in L

      3.2、可以使用map

    map(str, L)
    ''.join(str(x) for x in L)
    
    
    ''.join(map(str, L))
  • 相关阅读:
    代码是什么
    关于程序
    信息系统分析三原则
    设计的一个原则,妥协,不完美
    Algs4-1.4.30一个栈和一个steque实现的双向队列
    Algs4-1.4.31三个栈实现的双向队列
    Algs4-1.4.29两个栈实现的steque
    Algs4-1.4.27两个栈实现队列
    Algs4-1.4.28一个队列实现的栈
    *Algs4-1.4.26-三点共线-(未解决)
  • 原文地址:https://www.cnblogs.com/bcaixl/p/11532798.html
Copyright © 2011-2022 走看看