如何使用python中的算法将十进制转换为二进制

时间:2016-09-15 22:27:16

标签: python-3.x binary converter

请问这段代码有什么问题

def binary_converter(n):
    n = int(n)

    if n == 0:
        return '0'

    elif n not in (0,255):
        return 'Invalid input'


    elif n in range (0,255):
        return binary_converter(n//2) + str(n%2)


    else:
        return 'Invalid conversion'## Heading ##

here is the test
import unittest

class BinaryConverterTestCases(unittest.TestCase):
  def test_conversion_one(self):
    result = binary_converter(0)
    self.assertEqual(result, '0', msg='Invalid conversion')

  def test_conversion_two(self):
    result = binary_converter(62)
    self.assertEqual(result, '111110', msg='Invalid conversion')

  def test_no_negative_numbers(self):
    result = binary_converter(-1)
    self.assertEqual(result, 'Invalid input', msg='Input below 0 not allowed')

  def test_no_numbers_above_255(self):
    result = binary_converter(300)
    self.assertEqual(result, 'Invalid input', msg='Input above 255 not allowed')

1 个答案:

答案 0 :(得分:1)

首先,(0,255)是一个元组,而不是一系列数字,因此$ cat < props.xml <project> <echoproperties> <propertyset> <propertyref builtin="commandline"/> </propertyset> </echoproperties> </project> $ ant -f props.xml -Dfoo=bar -Dxyzzy=quoox Buildfile: /tmp/props.xml [echoproperties] #Ant properties [echoproperties] #Fri Sep 16 22:21:51 CEST 2016 [echoproperties] ant.file=/tmp/props.xml [echoproperties] ant.file.type=file [echoproperties] ant.project.invoked-targets= [echoproperties] foo=bar [echoproperties] xyzzy=quoox BUILD SUCCESSFUL Total time: 0 seconds 等等将失败,范围是半开的,所以2 in (0, 255)再次从range(0,255)开始0...254。您的第三次测试255 in range (0,255) -> False失败,因为您总是在基础案例中添加前导“0”,因此您self.assertEqual(result, '111110', msg='Invalid conversion')而不是'0111110'

'111110'

进行更改后,所有测试都应该通过。

您也可以迭代地执行此操作:

def binary_converter(n):
    n = int(n)
    if n == 0:
        return '0'
    # same as checking "if n in xrange(256)"
    if 0 <= n <= 255:
        return (binary_converter(n // 2) + str(n % 2)).lstrip("0")
    elif 0 > n or n > 255:
        return 'Invalid input'  ## Heading ##
    return 'Invalid conversion'  ## Heading ##