본문 바로가기

Python_Matter/Solve

Python Learn the basics Quiz 85

반응형

Q>

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 to string using several rules.

(여러 규칙을 사용하여 숫자를 문자열로 변환하는 함수를 작성해야합니다.)

First of all, you will need to cut the number with a given base (base argument; default 1000).

(우선, 주어진 기본 (기본 인수, 기본 1000)으로 번호를 잘라야합니다.)

The value is a float number with decimal after the point (decimals argument; default 0). For the value, use the rounding towards zero rule (5.6⇒5, -5.6⇒-5) if the decimal = 0, otherwise use the standard rounding procedure.

(값은 점 뒤에 십진수가있는 부동 소수점 숫자입니다 (decimals 인수, 기본값 0). 값의 경우 10 진수 = 0이면 반올림 0 규칙 (5.6⇒5, -5.6⇒-5)을 사용하고, 그렇지 않으면 표준 반올림 절차를 사용합니다.

If the number of decimals is greater than the current number of digits after dot, trail value with zeroes.

(소수점 이하 자릿수가 현재 점보다 큰 경우 점을 0으로 만듭니다.)

The number should be a value with letters designating the power.

(숫자는 글자가 힘을 나타내는 값이어야합니다.)

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 (suffix argument; default ‘’) , then you must append it.

(당신은 힘의 명단 (인자 '인자', '기본'[ ','k ','M ','G ','T ','P ','E ','Z ','Y '] ). 접미사 (접미사 인수, 기본값 '')가 주어진 경우 추가해야합니다.)

If you don’t have enough powers - stay at the maximum. And zero is always zero without powers, but with suffix.

(충분한 권한이없는 경우 - 최대 상태를 유지하십시오. 그리고 0은 힘이 없으면 항상 0이지만 접미사가 붙습니다.)

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 towards zero.
  • 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.

         (키워드 인수 "base"는 정수로, 기본값은 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'].

         (키워드 인수는 문자열 목록, 기본값 [ '', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']으로 "동력"입니다.)

 

Output: The converted number as a string.

           (변환 된 숫자를 문자열로 나타냅니다.)

 

Example:

friendly_number(102) == '102'
friendly_number(10240) == '10k'
friendly_number(12341234, decimals=1) == '12.3M'
friendly_number(12000000, decimals=3) == '12.000M'
friendly_number(12461, decimals=1) == '12.5k'
friendly_number(1024000000, base=1024, suffix='iB') == '976MiB'

 

How it is used: In the physics and IT we have a lot of various numbers.

                     (물리학과 IT에는 다양한 숫자가 많이 있습니다.)

                     Sometimes we need to make them more simpler and easier to read.

                     (때로는 더 간단하고 쉽게 읽을 수 있어야합니다.)

                     When you talk about gigabytes sometimes you don’t need to know the exact number bytes or                             kilobytes.

                     (기가 바이트에 대해 이야기 할 때 때때로 정확한 바이트 또는 킬로바이트를 알 필요가 없습니다.)

 

Precondition: 1 < base ≤ 1032
                   -1032 < number ≤ 1032
                   0 ≤ decimals ≤ 15
                   0 < len(powers) ≤ 32

 

A>

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.
    """
    # .copy 객체를 복사
    power_c = powers.copy()
    result, power = number, power_c.pop(0)

    while abs(result) >= base and power_c:
        if decimals:
            result /= base
        elif result < 0:
            result = int(result / base)
        else:
            result //= base
        power = power_c.pop(0)

    return '{:.{dec}f}{pw}{sf}'.format(result, pw=power, sf=suffix, dec=decimals)

#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
    assert friendly_number(102) == '102', '102'
    assert friendly_number(10240) == '10k', '10k'
    assert friendly_number(12341234, decimals=1) == '12.3M', '12.3M'
    assert friendly_number(12461, decimals=1) == '12.5k', '12.5k'
    assert friendly_number(1024000000, base=1024, suffix='iB') == '976MiB', '976MiB'

 

O>

Your result:"9kiB"

Pass:friendly_number(9000, suffix="iB")

 

S>

https://py.checkio.org

반응형

'Python_Matter > Solve' 카테고리의 다른 글

Python Learn the basics Quiz 87  (0) 2019.06.21
Python Learn the basics Quiz 86  (0) 2019.06.21
Python Learn the basics Quiz 84  (0) 2019.06.21
Python Learn the basics Quiz 83  (0) 2019.06.21
Python Learn the basics Quiz 82  (0) 2019.06.21