Skip to content

Commit 25dffd1

Browse files
committed
Problem10 solution
1 parent 2997b72 commit 25dffd1

File tree

2 files changed

+99
-23
lines changed

2 files changed

+99
-23
lines changed

10_telephone/telephone.py

+76
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Author : Luke McGuire <[email protected]>
4+
Date : 2024-06-27
5+
Purpose: Telephone
6+
"""
7+
8+
import argparse
9+
import os
10+
import random
11+
import string
12+
13+
14+
# --------------------------------------------------
15+
def float_percentage(s):
16+
"""check for float between 0 and 1"""
17+
try:
18+
value = float(s)
19+
except ValueError as e:
20+
raise argparse.ArgumentTypeError(f"invalid float value: '{s}'") from e
21+
if value < 0 or value >= 1:
22+
raise argparse.ArgumentTypeError(f'"{value}" must be between 0 and 1')
23+
return value
24+
25+
26+
# --------------------------------------------------
27+
def get_args():
28+
"""Get command-line arguments"""
29+
30+
parser = argparse.ArgumentParser(
31+
description="Telephone", formatter_class=argparse.ArgumentDefaultsHelpFormatter
32+
)
33+
34+
parser.add_argument("text", metavar="text", help="Input text or file")
35+
36+
parser.add_argument("-s", "--seed", help="Random seed", metavar="int", type=int)
37+
38+
parser.add_argument(
39+
"-m",
40+
"--mutations",
41+
help="Percent mutations",
42+
metavar="float",
43+
type=float_percentage,
44+
default=0.1,
45+
)
46+
47+
args = parser.parse_args()
48+
if os.path.isfile(args.text):
49+
with open(args.text, "rt", encoding="utf-8") as fh:
50+
args.text = fh.read().rstrip()
51+
52+
return args
53+
54+
55+
# --------------------------------------------------
56+
def main():
57+
"""Make a jazz noise here"""
58+
59+
args = get_args()
60+
text = args.text
61+
random.seed(args.seed)
62+
num_mutations = round(len(text) * args.mutations)
63+
alpha = "".join(sorted(string.ascii_letters + string.punctuation))
64+
scrambled = list(text)
65+
for i in random.sample(range(len(text)), k=num_mutations):
66+
scrambled[i] = random.choice(alpha.replace(text[i], ""))
67+
68+
scrambled = "".join(scrambled)
69+
70+
print(f'You said: "{text}"')
71+
print(f'I heard : "{scrambled}"')
72+
73+
74+
# --------------------------------------------------
75+
if __name__ == "__main__":
76+
main()

10_telephone/test.py

+23-23
Original file line numberDiff line numberDiff line change
@@ -7,33 +7,33 @@
77
import re
88
import string
99

10-
prg = "./telephone.py"
11-
fox = '../inputs/fox.txt'
12-
now = '../inputs/now.txt'
10+
PRG = "./telephone.py"
11+
FOX = "../inputs/fox.txt"
12+
NOW = "../inputs/now.txt"
1313

1414

1515
# --------------------------------------------------
1616
def test_exists():
1717
"""exists"""
1818

19-
assert os.path.isfile(prg)
19+
assert os.path.isfile(PRG)
2020

2121

2222
# --------------------------------------------------
2323
def test_usage():
2424
"""usage"""
2525

26-
for flag in ['', '-h', '--help']:
27-
out = getoutput(f'{prg} {flag}')
28-
assert re.match('usage', out, re.IGNORECASE)
26+
for flag in ["", "-h", "--help"]:
27+
out = getoutput(f"python3 {PRG} {flag}")
28+
assert re.match("usage", out, re.IGNORECASE)
2929

3030

3131
# --------------------------------------------------
3232
def test_bad_seed_str():
3333
"""bad seed str value"""
3434

3535
bad = random_string()
36-
rv, out = getstatusoutput(f'{prg} -s {bad} {fox}')
36+
rv, out = getstatusoutput(f"python3 {PRG} -s {bad} {FOX}")
3737
assert rv > 0
3838
assert re.search(f"invalid int value: '{bad}'", out)
3939

@@ -43,7 +43,7 @@ def test_bad_mutation_str():
4343
"""bad mutation str value"""
4444

4545
bad = random_string()
46-
rv, out = getstatusoutput(f'{prg} -m {bad} {fox}')
46+
rv, out = getstatusoutput(f"python3 {PRG} -m {bad} {FOX}")
4747
assert rv > 0
4848
assert re.search(f"invalid float value: '{bad}'", out)
4949

@@ -52,18 +52,18 @@ def test_bad_mutation_str():
5252
def test_bad_mutation():
5353
"""bad mutation values"""
5454

55-
for val in ['-1.0', '10.0']:
56-
rv, out = getstatusoutput(f'{prg} -m {val} {fox}')
55+
for val in ["-1.0", "10.0"]:
56+
rv, out = getstatusoutput(f"python3 {PRG} -m {val} {FOX}")
5757
assert rv > 0
58-
assert re.search(f'--mutations "{val}" must be between 0 and 1', out)
58+
assert re.search(f'--mutations: "{val}" must be between 0 and 1', out)
5959

6060

6161
# --------------------------------------------------
6262
def test_for_echo():
6363
"""test"""
6464

65-
txt = open(now).read().rstrip()
66-
rv, out = getstatusoutput(f'{prg} -m 0 "{txt}"')
65+
txt = open(NOW).read().rstrip()
66+
rv, out = getstatusoutput(f'python3 {PRG} -m 0 "{txt}"')
6767
assert rv == 0
6868
assert out.rstrip() == f'You said: "{txt}"\nI heard : "{txt}"'
6969

@@ -72,8 +72,8 @@ def test_for_echo():
7272
def test_now_cmd_s1():
7373
"""test"""
7474

75-
txt = open(now).read().rstrip()
76-
rv, out = getstatusoutput(f'{prg} -s 1 "{txt}"')
75+
txt = open(NOW).read().rstrip()
76+
rv, out = getstatusoutput(f'python3 {PRG} -s 1 "{txt}"')
7777
assert rv == 0
7878
expected = """
7979
Now is Ege time [dr all good me- to come to the jid of the party.
@@ -85,8 +85,8 @@ def test_now_cmd_s1():
8585
def test_now_cmd_s2_m4():
8686
"""test"""
8787

88-
txt = open(now).read().rstrip()
89-
rv, out = getstatusoutput(f'{prg} -s 2 -m .4 "{txt}"')
88+
txt = open(NOW).read().rstrip()
89+
rv, out = getstatusoutput(f'python3 {PRG} -s 2 -m .4 "{txt}"')
9090
assert rv == 0
9191
expected = """
9292
No$ i% khefMiIe sor@all$glo<BmenYts cAAeltaTtheSaid[HYnthe Aalty.
@@ -98,9 +98,9 @@ def test_now_cmd_s2_m4():
9898
def test_fox_file_s1():
9999
"""test"""
100100

101-
rv, out = getstatusoutput(f'{prg} --seed 1 {fox}')
101+
rv, out = getstatusoutput(f"python3 {PRG} --seed 1 {FOX}")
102102
assert rv == 0
103-
txt = open(fox).read().rstrip()
103+
txt = open(FOX).read().rstrip()
104104
expected = "The duic: brown hox jumps over the lkzy dog."
105105
assert out.rstrip() == f'You said: "{txt}"\nI heard : "{expected}"'
106106

@@ -109,9 +109,9 @@ def test_fox_file_s1():
109109
def test_fox_file_s2_m6():
110110
"""test"""
111111

112-
rv, out = getstatusoutput(f'{prg} --seed 2 --mutations .6 {fox}')
112+
rv, out = getstatusoutput(f"python3 {PRG} --seed 2 --mutations .6 {FOX}")
113113
assert rv == 0
114-
txt = open(fox).read().rstrip()
114+
txt = open(FOX).read().rstrip()
115115
expected = "ZoA@qric` HwdTB Alx$jumIslolXs th^Yl?dy<YoA."
116116
assert out.rstrip() == f'You said: "{txt}"\nI heard : "{expected}"'
117117

@@ -120,4 +120,4 @@ def test_fox_file_s2_m6():
120120
def random_string():
121121
"""generate a random filename"""
122122

123-
return ''.join(random.choices(string.ascii_lowercase + string.digits, k=5))
123+
return "".join(random.choices(string.ascii_lowercase + string.digits, k=5))

0 commit comments

Comments
 (0)