如果/其他选择 [英] If/else alternative
问题描述
我是编程新手,但我正在做一项任务。
我写了函数,以便用户输入的字节数量被翻译成可读的格式。基本上返回适当的B,KB,MB,GB,TB。然而,这个任务说我们应该尝试编写没有循环或者语句的代码,但是我们可以使用数组。
我想知道我该怎么做...
这是我现在的代码:
def memory_size(n):
if n < 1024:
print n,B
if 1024< = n< 1048576:
nKB = n / 1024
打印nKB,KB
1048576 <= n < 1073741824:
nMB =(n / 1024)/ 1024
打印nMB,MB
如果1073741824 <= n < 1.099511628 *(10 ** 12):
nGB =((n / 1024)/ 1024)/ 1024
print nGB,GB
if 1.099511628 *(10 ** 12)< ; = n< 1.125899907 *(10 ** 15):
nTB =(((n / 1024)/ 1024)/ 1024)/ 1024
print nTB,TB
因为这是一项家庭作业,我不会发布整个代码,只是想说它可以通过几行方式实现。
仔细查看 math
库,特别是 pow
和 log
您可以像这样定义范围:
>>>范围= ['B','KB','MB','GB','TB']
然后 $ b
-
log
ofn
并截断小数。 - 使用
math.pow
和#1中的值计算大小 - 打印大小并通过使用#1中的数字来查找
范围
数组以获得值b,kb,mb等等。
这样您就不会使用任何 if / else
语句或 for / while
循环。
I'm new to programming, but I'm doing a task for an assignment. I've written function so that the amount of Bytes that the user enters is translated into a "human readable" format. Basically to return in the appropriate B,KB,MB,GB,TB.
However, the assignment says we should try writing the code without loops or if statements, but we can use an array.
I was wondering how I might do this...
Here's my current code:
def memory_size(n):
if n < 1024:
print n,"B"
if 1024 <= n < 1048576:
nKB = n / 1024
print nKB,"KB"
if 1048576 <= n < 1073741824:
nMB = (n / 1024) / 1024
print nMB,"MB"
if 1073741824 <= n < 1.099511628*(10**12):
nGB = ((n / 1024) / 1024) / 1024
print nGB,"GB"
if 1.099511628*(10**12) <= n < 1.125899907*(10**15):
nTB =(((n / 1024) / 1024) / 1024) / 1024
print nTB,"TB"
Because this is a homework, I'm not going to post a whole code, just going to say that it can feat in a few lines.
take a look at math
library specifically to pow
and log
You can define you ranges like this:
>>> ranges = ['B', 'KB', 'MB', 'GB', 'TB']
Then
log
ofn
and truncate decimal.- Calculate the size, using
math.pow
and the value from #1 - Print the size and do a lookup to the
ranges
array by using number from #1 to get a value "b, kb, mb and so on".
This way you will not use any if/else
statements or for/while
loops.
这篇关于如果/其他选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!