Skip to content

Commit 3efbb6b

Browse files
keynguyenBkeynguyen2004
authored andcommitted
Update fix-phone-num.py
1 parent c04789c commit 3efbb6b

File tree

1 file changed

+19
-13
lines changed

1 file changed

+19
-13
lines changed

fix-phone-num.py

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,27 @@
11
import pytest
22

33
def fix_phone_num(phone_num_to_fix):
4-
if len(phone_num_to_fix) == 11 and phone_num_to_fix[0] == "1":
5-
phone_num_to_fix = phone_num_to_fix[1:] # Remove the country code "1"
4+
5+
if len(phone_num_to_fix) == 11:
6+
# The phone number is of length 11, so check if it has the "1" country code.
7+
if phone_num_to_fix[0] != "1":
8+
# The country code wasn't a "1", so the number is invalid.
9+
raise ValueError(f"phone numbers of length 11 must begin with a 1, got \"{phone_num_to_fix}\"")
10+
# Strip off the country code "1" from the beginning.
11+
# Resulting string should be of length 10 to work with formatting code below.
12+
phone_num_to_fix = phone_num_to_fix[1:]
613

714
if len(phone_num_to_fix) != 10:
815
raise ValueError(f"phone number must be length 10; got \"{phone_num_to_fix}\" which is of length {len(phone_num_to_fix)}")
9-
1016
if not phone_num_to_fix.isdigit():
1117
raise ValueError(f"phone number must only contain digits; got \"{phone_num_to_fix}\"")
12-
18+
1319
# given "5125558823". Split the parts, then recombine and return
1420
area_code = phone_num_to_fix[0:3] # 512 (first three digits)
1521
three_part = phone_num_to_fix[3:6] # 555 (next three digits)
16-
four_part = phone_num_to_fix[6:] # 8823 (last four digits)
22+
four_part = phone_num_to_fix[6:] # # 8823 (last four digits)
1723

18-
fixed_num = f"({area_code}) {three_part} {four_part}"
24+
fixed_num = "(" + area_code + ")" + " " + three_part + " " + four_part
1925

2026
return fixed_num
2127

@@ -30,20 +36,20 @@ def test_fix_phone_num3():
3036
assert fix_phone_num("3216543333") == '(321) 654 3333'
3137

3238
def test_short_num_error():
33-
with pytest.raises(ValueError):
34-
fix_phone_num("51")
39+
with pytest.raises(ValueError):
40+
fix_phone_num("51")
3541

3642
def test_long_num_error():
37-
with pytest.raises(ValueError):
38-
fix_phone_num("01234567890")
43+
with pytest.raises(ValueError):
44+
fix_phone_num("01234567890")
3945

4046
def test_non_digit_error():
41-
with pytest.raises(ValueError):
42-
fix_phone_num("012345678a")
47+
with pytest.raises(ValueError):
48+
fix_phone_num("012345678a")
4349

4450
def test_fix_phone_num_country_code():
4551
assert fix_phone_num("15125558823") == '(512) 555 8823'
4652

4753
def test_wrong_country_code():
4854
with pytest.raises(ValueError):
49-
fix_phone_num("25125558823")
55+
assert fix_phone_num("25125558823")

0 commit comments

Comments
 (0)