Friendly number
Friendly number
Long numbers can be made to look nicer, so let’s write some code to do just that.
You should write a function for converting a number using several rules. For starters, you will need to cut the number with a given base (base argument; default 1000). The number should be a coefficient with letters designating the power. The coefficient is a real number with decimal after the point (decimals argument; default 0). You will be given a list of power designations (powers argument; default ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']). If you are given suffix (suffixargument; default ‘’) , then you must be add it at the end. For the coefficient, use the rounding down rule (5.6⇒5, -5.6⇒-5) if the decimal = 0, else use the standard rounding procedure. If you don’t have enough powers - stay at the maximum. If the number of decimals are greater than the real number of digits after dot, trail it with zeroes. And zero is always zero without powers.
Let's look at examples. It will be simpler.
- n=102
result: "102", the base is default 1000 and 102 is lower this base. - n=10240
result: "10k", the base is default 1000 and rounding down. - n=12341234, decimals=1
result: "12.3M", one digit after the dot. - n=12000000, decimals=3
result: "12.000M", trailing zeros. - n=12461, decimals=1
result: "12.5k", standard rounding. - n=1024000000, base=1024, suffix='iB'
result: '976MiB', the different base and the suffix. - n=-150, base=100, powers=['', 'd', 'D']
result: '-1d', the negative number and rounding down. - n=-155, base=100, decimals=1, powers=['', 'd', 'D']
result: '-1.6d', the negative number and standard rounding. - n=255000000000, powers=['', 'k', 'M']
result: '255000M', there is not enough powers.
Input: A number as an integer. The keyword argument "base" as an integer, default 1000. The keyword argument "decimals" as an integer, default 0. The keyword argument "powers" as a list of string, default ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'].
Output: The converted number as a string.
原题链接: http://www.checkio.org/mission/friendly-number/
题目大义: 将给定的数字, 按照传入的参数, 如小数位, base, 幂次, 及后缀
思路: 熟悉python的数值计算, 在python3之后, /执行的是真正的除法, 通过代码实际运行情况, 发现/的结果均为float型, 无论除数被除数; 另外python3支持大整数, 而在大整数执行/运算时, 结果可能有偏差, 如在本题中
>>> i = 10 ** 32
>>> i /= 1000
>>> i
1e+29
>>> i /= 1000
>>> i
9.999999999999999e+25
以上为在我电脑上python3.4.1的运行结果
可以通过使用Decimal解决这个问题, 代码如下
from decimal import Decimal def friendly_number(number, base=1000, decimals=0, suffix='',
powers=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']):
"""
Format a number as friendly text, using common suffixes.
"""
step = 0
powers_len = len(powers) - 1 number = Decimal(number) while abs(number) >= base and step < powers_len:
step += 1
number /= base if decimals != 0:
coefficent = round(number, decimals)
else:
coefficent = int(number) return '%.*f' % (decimals, coefficent) + powers[step] + suffix
注意最后一行的写法, 保留小数点位数的形式与c语言类似
review Sim0000's codes
def friendly_number(number, base=1000, decimals=0, suffix='',
powers=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']):
# At first, decompose the number to value and exponent.
e = 0
while e + 1 < len(powers) and abs(number) >= base ** (e + 1) : e += 1
number /= base ** e
# Then round it.
number = round(number, decimals) if decimals else int(number)
# At last, Format it.
return '{:.0f}'.replace('', str(decimals)).format(number) + powers[e] + suffix
思路一致, 注意第10行的用法, 冒号后是格式控制
Friendly number的更多相关文章
- genToken- Php file
<?php public function genToken($len = 32, $md5 = true) { # Seed random number generator # Only ne ...
- 防止php重复提交表单更安全的方法
Token.php <?php /* * Created on 2013-3-25 * * To change the template for this generated file go t ...
- php表单加入Token防止重复提交的方法分析
http://www.jb51.net/article/94395.htm 这篇文章主要介绍了php表单加入Token防止重复提交的方法,结合实例形式分析了Token防止重复提交的原理与使用技巧,需要 ...
- Java访问权限修饰符public protected friendly private用法总结(转载好文Mark)
首先声明:Java中,friendly这个修饰符并没有显式的声明,在成员变量和方法前什么修饰符也不用,默认的就是friendly.为了条理清晰,分三种不同情况来总结. 一 访问权限修饰符修饰成员变量和 ...
- Fibonacci number
https://github.com/Premiumlab/Python-for-Algorithms--Data-Structures--and-Interviews/blob/master/Moc ...
- 关于Java的权限修饰符(public,private,protected,默认friendly)
以前对访问修饰符总是模棱两可,让自己仔细解释也是经常说不很清楚.这次要彻底的搞清楚. 现在总结如下: 一.概括总结 各个访问修饰符对不同包及其子类,非子类的访问权限 Java访问权限修饰符包含四个:p ...
- Codeforces Gym 100269K Kids in a Friendly Class 构造题
Kids in a Friendly Class 题目连接: http://codeforces.com/gym/100269/attachments Description Kevin resemb ...
- HDU-6534-Chika and Friendly Pairs (莫队算法,树状数组,离散化)
链接: https://vjudge.net/contest/308446#problem/C 题意: Chika gives you an integer sequence a1,a2,-,an a ...
- JavaScript Math和Number对象
目录 1. Math 对象:数学对象,提供对数据的数学计算.如:获取绝对值.向上取整等.无构造函数,无法被初始化,只提供静态属性和方法. 2. Number 对象 :Js中提供数字的对象.包含整数.浮 ...
随机推荐
- 利用php unpack读取c struct的二进制数据,struct内存对齐引起的一些问题
c语言代码 #include <stdio.h> struct test{ int a; unsigned char b; int c; }; int main(){ FILE *fp; ...
- java集合经常出现空指针问题的解决方案
我自己问自己这个问题的时候都把自己给雷住了,但是现实如此,经常写的程序就是出现空指针的错误. 如: public List add(){ List list=null; try { list=new ...
- 【转】Date类学习总结(Calendar Date 字符串 相互转换 格式化)
原文网址:http://www.blogjava.net/jerry-zhaoj/archive/2008/10/08/233228.html Date类学习总结 1.计算某一月份的最大天数 Cale ...
- bzoj1624 [Usaco2008 Open] Clear And Present Danger 寻宝之路
Description 农夫约翰正驾驶一条小艇在牛勒比海上航行. 海上有N(1≤N≤100)个岛屿,用1到N编号.约翰从1号小岛出发,最后到达N号小岛.一 张藏宝图上说,如果他的路程上 ...
- 关于Set Nocount ON的性能 |c#调用存储过程的返回值总是-1
原文地址:http://www.tuicool.com/articles/qe6BZbR 也许因为它太过于简单,自己一直没能好好关注这个语句,只记得"只是"提高点性能而已.有时会在存储过程中写上几句, ...
- CSMA/CD协议
为了通信的简便,以太网采取了两种重要的措施: 第一:采用较为灵活的无连接的工作方式,即不必先建立连接就可以直接发送数据: 第二:以太网对发送的数据帧不进行编号,也不要求对方发回确认. 因此,以太网提供 ...
- 普通用户之间的ssh无密码访问设置方法
两台CentOS6.2服务器,客户端是node1,服务器是node2,先都用root用户配置,方法如下: 第一步:在客户端Node1:生成密匙对,我用的是rsa的密钥.使用命令 "ssh-k ...
- Link all references for a local rename (does not change references in other files)
这是一个十分easy的问题 错误原因 : import Android.R; 把这句话去掉 ctrl + shift+o 引进一个 项目对应的R文件 R存在于gen文件夹下 可以找到 layo ...
- poj1064 二分,注意精度!
Cable master Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 35269 Accepted: 7513 Des ...
- HDU 5044 离线LCA算法
昨天写了HDU 3966 ,本来这道题是很好解得,结果我想用离线LCA 耍一把,结果发现离线LCA 没理解透,错了好多遍,终得AC ,这题比起 HDU 3966要简单,因为他不用动态查询.但是我还是错 ...