博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Kata Daily 190917】Numericals of a String(字符出现的次数)
阅读量:4344 次
发布时间:2019-06-07

本文共 1295 字,大约阅读时间需要 4 分钟。

题目:

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 defaultdictdef 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 Counterdef 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))

 

转载于:https://www.cnblogs.com/bcaixl/p/11532798.html

你可能感兴趣的文章
Detours信息泄漏漏洞
查看>>
win32使用拖放文件
查看>>
Android 动态显示和隐藏软键盘
查看>>
raid5什么意思?怎样做raid5?raid5 几块硬盘?
查看>>
【转】how can i build fast
查看>>
null?对象?异常?到底应该如何返回错误信息
查看>>
django登录验证码操作
查看>>
(简单)华为Nova青春 WAS-AL00的USB调试模式在哪里开启的流程
查看>>
图论知识,博客
查看>>
[原创]一篇无关技术的小日记(仅作暂存)
查看>>
20145303刘俊谦 Exp7 网络欺诈技术防范
查看>>
原生和jQuery的ajax用法
查看>>
iOS开发播放文本
查看>>
20145202马超《java》实验5
查看>>
JQuery 事件
查看>>
main(argc,argv[])
查看>>
第四阶段 15_Linux tomcat安装与配置
查看>>
NAS 创建大文件
查看>>
学习笔记-模块之xml文件处理
查看>>
接口测试用例
查看>>