2016-09-15 15 views
1

にアルゴリズムを使用してバイナリに小数を変換するために、何がこのコードが間違っているしてください方法のpython

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') 
+0

理由は特殊なケースですか? –

+0

@DarthKotikテストでは無効な入力を返すことになっています。 – David

+0

@PadraicCunninghamあなたの正しいが、私はまだそれを提出するときにエラーが発生します.P/Sそれはandela家庭研究のための割り当てです..私は本当にこれを正しく学ぶためには完全なコードではなく、アドバイスが必要です。ありがとうすべて – David

答えて

1

まず、(0、255)するタプルない番号の範囲ですので2 in (0, 255)など。です範囲が半開になるのでrange(0,255)0...254から、255 in range (0,255) -> Falseになります。

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 ## 

あなたはすべてのテストに合格しなければならない変更を加えたら:あなたが'0111110'ない'111110'を取得するので、あなたは常にあなたの基本ケースでは先頭の「0」を追加すると、あなたの第三の試験self.assertEqual(result, '111110', msg='Invalid conversion')は失敗します。

あなたはまた、反復的にそれを行うことができます:地球62上の

def binary_converter(n): 
    if n < 0 or n > 255: 
     return "Invalid input" 
    tmp = [] 
    while n: 
     n, i = divmod(n, 2) 
     tmp.append(str(i)) 
    return "".join(tmp[::-1] or "0") 
+0

あなたは私に大きな恩恵をもたらしました..私はそれがちょうどいくつかのバグを見逃していたことに気づきませんでした..本当にありがとう、ありがとう。 – David

+0

心配はいりません。どうぞよろしくお願いいたします。 –