Python刷题笔记(2)- 取5位大数字
2015-11-17 11:22
1616 查看
又到codewar每日刷题时刻,今天抽到的题依旧是难度5
91 is the greatest sequence of 2 digits.
Complete the solution so that it returns the largest five digit number found within the number given.. The number will be passed in as a string of only digits. It should return a five digit integer. The number passed may be as large as 1000 digits.
Adapted from ProjectEuler.net
2.数字大小可以根据首位数的大小进行筛选,这样可以减少一大部分运算,可以通过集合来判断首位最大数
3.从原字符串中截取首位为最大数的5位连续数字,建立列表,然后进行排序
题目:
In the following 6 digit number:283910
91 is the greatest sequence of 2 digits.
Complete the solution so that it returns the largest five digit number found within the number given.. The number will be passed in as a string of only digits. It should return a five digit integer. The number passed may be as large as 1000 digits.
Adapted from ProjectEuler.net
中文简介:
从输入的若干连续数字(输入为字符串)中提取其中连续的最大5位数(整数输出)想法:
1.最大连续5位数,首先想到的是历遍每个数位,然后截取连续的5位进行,不过这样数字位太多的时候过于繁杂2.数字大小可以根据首位数的大小进行筛选,这样可以减少一大部分运算,可以通过集合来判断首位最大数
3.从原字符串中截取首位为最大数的5位连续数字,建立列表,然后进行排序
实现:
def solution(digits): big = sorted([ i for i in set(digits) ])[-1] #获取digits中最大数字 num_list = [digits[:5]] #仅有5位数 for i in range(len(digits)-4): if digits[i] == big: num_list.append(digits[i:i+5]) #获取首位跟最大数字相等的5位数,放入列表 return int(sorted(num_list)[-1]) #将列表排序,获取列表中最大数切片,并转化为整数
对比总结:
提交后,发现原来有max()函数可以直接取最大值,不用我用的sorted()再取切片那么麻烦,另外最好练习的人是直接历遍函数取切片然后用max获取最大值的,看来先比较首字母可能反而是我想多了。。相关文章推荐
- Python字符串处理
- python torndb模块
- Python性能鸡汤
- 动手实践:在Windows上安装NumPy
- python自动化框架nose
- 【NumPy学习指南】day5 改变数组的维度
- [转]python socket编程
- windows平台如何安装Python和pip
- LeetCode OJ 系列之283 Move Zeroes --Python
- Python+Django+Eclipse 在Windows下快速开发自己的网站
- Python篇----正则表达式语法(基础)
- 【python】python入门篇:python安装和环境配置、pycharm安装、第一个python程序hello world
- 学习Python(二)
- supervisor - Python进程管理工具(转)
- [151116 记录] 使用Python3.5爬取豆瓣电影Top250
- 使用 Python 编写 vim 插件
- python父线程关闭后子线程不关闭问题
- Python神图
- python 关于dict的一些总结
- python 实现 Dijkstra最短路径问题