Skip to content

Commit 1ae7e48

Browse files
committed
Merge pull request #9 from sjakobi/octal
2 parents 4450501 + 36d2dd9 commit 1ae7e48

File tree

3 files changed

+59
-0
lines changed

3 files changed

+59
-0
lines changed

EXERCISES.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ anagram
66
beer-song
77
nucleotide-count
88
series
9+
octal
910
point-mutations
1011
phone-number
1112
grade-school

octal/example.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Octal(object):
2+
def __init__(self, octal_string):
3+
self.digits = self.__validate(octal_string)
4+
5+
def __validate(self, s):
6+
for char in s:
7+
if not '0' <= char < '8':
8+
raise ValueError("Invalid octal digit: " + char)
9+
return s
10+
11+
def to_decimal(self):
12+
return sum(int(digit) * 8 ** i
13+
for (i, digit) in enumerate(reversed(self.digits)))

octal/octal_test.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
try:
2+
from octal import Octal
3+
except ImportError:
4+
raise SystemExit('Could not find octal.py. Does it exist?')
5+
6+
import unittest
7+
8+
9+
class OctalTest(unittest.TestCase):
10+
def test_octal_1_is_decimal_1(self):
11+
self.assertEqual(1, Octal("1").to_decimal())
12+
13+
def test_octal_10_is_decimal_8(self):
14+
self.assertEqual(8, Octal("10").to_decimal())
15+
16+
def test_octal_17_is_decimal_15(self):
17+
self.assertEqual(15, Octal("17").to_decimal())
18+
19+
def test_octal_130_is_decimal_88(self):
20+
self.assertEqual(88, Octal("130").to_decimal())
21+
22+
def test_octal_2047_is_decimal_1063(self):
23+
self.assertEqual(1063, Octal("2047").to_decimal())
24+
25+
def test_octal_1234567_is_decimal_342391(self):
26+
self.assertEqual(342391, Octal("1234567").to_decimal())
27+
28+
def test_8_is_seen_as_invalid(self):
29+
self.assertRaisesRegexp(ValueError, "^Invalid octal digit: 8$",
30+
Octal, "8")
31+
32+
def test_invalid_octal_is_recognized(self):
33+
self.assertRaisesRegexp(ValueError, "^Invalid octal digit: c$",
34+
Octal, "carrot")
35+
36+
def test_6789_is_seen_as_invalid(self):
37+
self.assertRaisesRegexp(ValueError, "^Invalid octal digit: 8$",
38+
Octal, "6789")
39+
40+
def test_valid_octal_formatted_string_011_is_decimal_9(self):
41+
self.assertEqual(9, Octal("011").to_decimal())
42+
43+
44+
if __name__ == '__main__':
45+
unittest.main()

0 commit comments

Comments
 (0)