1
私はこのチャレンジを持っています:私のPythonコードがユニットテストに失敗するのはなぜですか?
binary_converterという名前の関数を作成します。この関数の内部では、0〜255の10進数を2進数に変換するアルゴリズムを実装します。無効な入力、返される文字列の無効な入力の場合
例:数5返される文字列の場合は101
ユニットテストコードは
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')
私のコードは
下回る下回っていますdef binary_converter(n):
if(n==0):
return "0"
elif(n>255):
return "invalid input"
elif(n < 0):
return "invalid input"
else:
ans=""
while(n>0):
temp=n%2
ans=str(temp)+ans
n=n/2
return ans
単体テスト結果
Total Specs: 4 Total Failures: 2
1. test_no_negative_numbers
`Failure in line 19, in test_no_negative_numbers self.assertEqual(result, 'Invalid input', msg='Input below 0 not allowed') AssertionError: Input below 0 not allowed`
2. test_no_numbers_above_255
`Failure in line 23, in test_no_numbers_above_255 self.assertEqual(result, 'Invalid input', msg='Input above 255 not allowed') AssertionError: Input above 255 not allowed`
「無効」!=「無効」ですか? – HorusKol
心配する必要はありません。あなたは問題を見ずに、そんなことをいつまでも楽しみたいと思っています。 – HorusKol