response
stringlengths 1
33.1k
| instruction
stringlengths 22
582k
|
---|---|
Test choose | def test_choose():
"""Test choose"""
state = random.getstate()
random.seed(1)
assert choose('a') == 'a'
assert choose('b') == 'b'
assert choose('c') == 'C'
assert choose('d') == 'd'
random.setstate(state) |
exists | def test_exists():
"""exists"""
assert os.path.isfile(prg) |
usage | def test_usage():
"""usage"""
for flag in ['-h', '--help']:
rv, out = getstatusoutput(f'{prg} {flag}')
assert rv == 0
assert re.match("usage", out, re.IGNORECASE) |
Test | def test_text1():
"""Test"""
in_text = 'The quick brown fox jumps over the lazy dog.'
tests = [('1', 'thE QUICk BrOWn Fox jumpS OveR tHe LAzY dOg.'),
('3', 'thE quICk BROwn Fox jUmPS OVEr the lAZY DOG.')]
for seed, expected in tests:
rv, out = getstatusoutput(f'{prg} {seed_flag()} {seed} "{in_text}"')
assert rv == 0
assert out.strip() == expected |
Test | def test_text2():
"""Test"""
in_text = 'Now is the time for all good men to come to the aid of the party.'
tests = [
('2',
'now iS the TIME fOR ALl good meN TO COMe To THE AID oF THE PArTY.'),
('5',
'NOw is tHE Time FOr all good men To coME TO tHe AiD OF THe ParTy.')
]
for seed, expected in tests:
rv, out = getstatusoutput(f'{prg} {seed_flag()} {seed} "{in_text}"')
assert rv == 0
assert out.strip() == expected |
Test | def test_file1():
"""Test"""
tests = [('1', 'thE QUICk BrOWn Fox jumpS OveR tHe LAzY dOg.'),
('3', 'thE quICk BROwn Fox jUmPS OVEr the lAZY DOG.')]
for seed, expected in tests:
rv, out = getstatusoutput(f'{prg} {seed_flag()} {seed} {fox}')
assert rv == 0
assert out.strip() == expected |
Test | def test_file2():
"""Test"""
tests = [
('2',
'now iS the TIME fOR ALl good meN TO COMe To THE AID oF THE PArTY.'),
('5',
'NOw is tHE Time FOr all good men To coME TO tHe AiD OF THe ParTy.')
]
for seed, expected in tests:
rv, out = getstatusoutput(f'{prg} {seed_flag()} {seed} {now}')
assert rv == 0
assert out.strip() == expected |
Get command-line arguments | def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Twelve Days of Christmas',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-n',
'--num',
help='Number of days to sing',
metavar='days',
type=int,
default=12)
parser.add_argument('-o',
'--outfile',
help='Outfile',
metavar='FILE',
type=argparse.FileType('wt'),
default=sys.stdout)
args = parser.parse_args()
if args.num not in range(1, 13):
parser.error(f'--num "{args.num}" must be between 1 and 12')
return args |
Make a jazz noise here | def main():
"""Make a jazz noise here"""
args = get_args()
verses = map(verse, range(1, args.num + 1))
print('\n\n'.join(verses), file=args.outfile) |
Create a verse | def verse(day):
"""Create a verse"""
ordinal = [
'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh',
'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth'
]
gifts = [
'A partridge in a pear tree.',
'Two turtle doves,',
'Three French hens,',
'Four calling birds,',
'Five gold rings,',
'Six geese a laying,',
'Seven swans a swimming,',
'Eight maids a milking,',
'Nine ladies dancing,',
'Ten lords a leaping,',
'Eleven pipers piping,',
'Twelve drummers drumming,',
]
lines = [
f'On the {ordinal[day - 1]} day of Christmas,',
'My true love gave to me,'
]
lines.extend(reversed(gifts[:day]))
if day > 1:
lines[-1] = 'And ' + lines[-1].lower()
return '\n'.join(lines) |
Test verse | def test_verse():
"""Test verse"""
assert verse(1) == '\n'.join([
'On the first day of Christmas,', 'My true love gave to me,',
'A partridge in a pear tree.'
])
assert verse(2) == '\n'.join([
'On the second day of Christmas,', 'My true love gave to me,',
'Two turtle doves,', 'And a partridge in a pear tree.'
]) |
Get command-line arguments | def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Twelve Days of Christmas',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-n',
'--num',
help='Number of days to sing',
metavar='days',
type=int,
default=12)
parser.add_argument('-o',
'--outfile',
help='Outfile',
metavar='FILE',
type=argparse.FileType('wt'),
default=sys.stdout)
args = parser.parse_args()
if args.num not in range(1, 13):
parser.error(f'--num "{args.num}" must be between 1 and 12')
return args |
Make a jazz noise here | def main():
"""Make a jazz noise here"""
args = get_args()
verses = map(verse, range(1, args.num + 1))
print(emoji.emojize('\n\n'.join(verses)), file=args.outfile) |
Create a verse | def verse(day):
"""Create a verse"""
ordinal = [
'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh',
'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth'
]
gifts = [
'A :bird: in a pear tree.',
'Two turtle :bird:s,',
'Three French :bird:s,',
'Four calling :bird:s,',
'Five gold :ring:s,',
'Six :bird:s a laying,',
'Seven :bird:s a swimming,',
'Eight :woman:s a milking,',
'Nine :woman:s dancing,',
'Ten :man:s a leaping,',
'Eleven :man:s piping,',
'Twelve :drum:s drumming,',
]
lines = [
f'On the {ordinal[day - 1]} day of Christmas,',
'My true love gave to me,'
]
lines.extend(reversed(gifts[:day]))
if day > 1:
lines[-1] = 'And ' + lines[-1].lower()
return '\n'.join(lines) |
Test verse | def test_verse():
"""Test verse"""
assert verse(1) == '\n'.join([
'On the first day of Christmas,', 'My true love gave to me,',
'A :bird: in a pear tree.'
])
assert verse(2) == '\n'.join([
'On the second day of Christmas,', 'My true love gave to me,',
'Two turtle :bird:s,', 'And a :bird: in a pear tree.'
]) |
exists | def test_exists():
"""exists"""
assert os.path.isfile(prg) |
usage | def test_usage():
"""usage"""
for flag in ['-h', '--help']:
rv, out = getstatusoutput(f'{prg} {flag}')
assert rv == 0
assert re.match("usage", out, re.IGNORECASE) |
test bad_num | def test_bad_num():
"""test bad_num"""
for n in [random.choice(r) for r in (range(-10, -1), range(13, 20))]:
rv, out = getstatusoutput(f'{prg} -n {n}')
assert rv != 0
assert re.search(f'--num "{n}" must be between 1 and 12', out) |
test one | def test_one():
"""test one"""
out = getoutput(f'{prg} -n 1')
assert out.rstrip() == day_one |
test two | def test_two():
"""test two"""
out = getoutput(f'{prg} --num 2')
assert out == '\n\n'.join([day_one, day_two]) |
test | def test_all_stdout():
"""test"""
out = getoutput(f'{prg}').splitlines()
assert len(out) == 113
assert out[0] == 'On the first day of Christmas,'
assert out[-1] == 'And a partridge in a pear tree.' |
Test 1-12 | def test_all():
"""Test 1-12"""
test_out = './test-out'
assert os.path.isdir(test_out)
for n in range(1, 13):
print(n)
# Normal run (STDOUT)
expected_file = os.path.join(test_out, f'{n}.out')
assert os.path.isfile(expected_file)
expected = open(expected_file).read().rstrip()
cmd = f'{prg} -n {n}'
out = getoutput(cmd).rstrip()
assert out == expected
# Run with --outfile
out_file = random_string()
if os.path.isfile(out_file):
os.remove(out_file)
try:
out = getoutput(cmd + f' -o {out_file}').rstrip()
assert out == ''
assert os.path.isfile(out_file)
output = open(out_file).read().rstrip()
assert len(output.split('\n')) == len(expected.split('\n'))
assert output.rstrip() == expected.rstrip()
finally:
if os.path.isfile(out_file):
os.remove(out_file) |
generate a random string | def random_string():
"""generate a random string"""
k = random.randint(5, 10)
return ''.join(random.choices(string.ascii_letters + string.digits, k=k)) |
get command-line arguments | def get_args():
"""get command-line arguments"""
parser = argparse.ArgumentParser(
description='Make rhyming "words"',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('word', metavar='word', help='A word to rhyme')
return parser.parse_args() |
Make a jazz noise here | def main():
"""Make a jazz noise here"""
args = get_args()
prefixes = list('bcdfghjklmnpqrstvwxyz') + (
'bl br ch cl cr dr fl fr gl gr pl pr sc '
'sh sk sl sm sn sp st sw th tr tw thw wh wr '
'sch scr shr sph spl spr squ str thr').split()
start, rest = stemmer(args.word)
if rest:
print('\n'.join(sorted([p + rest for p in prefixes if p != start])))
else:
print(f'Cannot rhyme "{args.word}"') |
Return leading consonants (if any), and 'stem' of word | def stemmer(word):
"""Return leading consonants (if any), and 'stem' of word"""
word = word.lower()
vowels = 'aeiou'
consonants = ''.join(
[c for c in string.ascii_lowercase if c not in vowels])
pattern = (
'([' + consonants + ']+)?' # capture one or more, optional
'([' + vowels + '])' # capture at least one vowel
'(.*)' # capture zero or more of anything
)
pattern = f'([{consonants}]+)?([{vowels}])(.*)'
match = re.match(pattern, word)
if match:
p1 = match.group(1) or ''
p2 = match.group(2) or ''
p3 = match.group(3) or ''
return (p1, p2 + p3)
else:
return (word, '') |
test the stemmer | def test_stemmer():
"""test the stemmer"""
assert stemmer('') == ('', '')
assert stemmer('cake') == ('c', 'ake')
assert stemmer('chair') == ('ch', 'air')
assert stemmer('APPLE') == ('', 'apple')
assert stemmer('RDNZL') == ('rdnzl', '')
assert stemmer('123') == ('123', '') |
get command-line arguments | def get_args():
"""get command-line arguments"""
parser = argparse.ArgumentParser(
description='Make rhyming "words"',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('word', metavar='str', help='A word to rhyme')
return parser.parse_args() |
Make a jazz noise here | def main():
"""Make a jazz noise here"""
args = get_args()
prefixes = list('bcdfghjklmnpqrstvwxyz') + (
'bl br ch cl cr dr fl fr gl gr pl pr sc '
'sh sk sl sm sn sp st sw th tr tw thw wh wr '
'sch scr shr sph spl spr squ str thr').split()
start, rest = stemmer(args.word)
if rest:
print('\n'.join(sorted([p + rest for p in prefixes if p != start])))
else:
print(f'Cannot rhyme "{args.word}"') |
Return leading consonants (if any), and 'stem' of word | def stemmer(word):
"""Return leading consonants (if any), and 'stem' of word"""
word = word.lower()
vowel_pos = list(map(word.index, filter(lambda v: v in word, 'aeiou')))
if vowel_pos:
first_vowel = min(vowel_pos)
return (word[:first_vowel], word[first_vowel:])
else:
return (word, '') |
test the stemmer | def test_stemmer():
"""test the stemmer"""
assert stemmer('') == ('', '')
assert stemmer('cake') == ('c', 'ake')
assert stemmer('chair') == ('ch', 'air')
assert stemmer('APPLE') == ('', 'apple')
assert stemmer('RDNZL') == ('rdnzl', '')
assert stemmer('123') == ('123', '') |
get command-line arguments | def get_args():
"""get command-line arguments"""
parser = argparse.ArgumentParser(
description='Make rhyming "words"',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('word', metavar='str', help='A word to rhyme')
parser.add_argument('-w',
'--wordlist',
metavar='FILE',
type=argparse.FileType('r'),
default='/usr/share/dict/words',
help='Wordlist to verify authenticity')
return parser.parse_args() |
Make a jazz noise here | def main():
"""Make a jazz noise here"""
args = get_args()
prefixes = list('bcdfghjklmnpqrstvwxyz') + (
'bl br ch cl cr dr fl fr gl gr pl pr sc '
'sh sk sl sm sn sp st sw th tr tw thw wh wr '
'sch scr shr sph spl spr squ str thr').split()
dict_words = read_wordlist(args.wordlist)
def is_dict_word(word):
return word.lower() in dict_words if dict_words else True
start, rest = stemmer(args.word)
if rest:
print('\n'.join(
sorted(
filter(is_dict_word,
[p + rest for p in prefixes if p != start]))))
else:
print(f'Cannot rhyme "{args.word}"') |
Return leading consonants (if any), and 'stem' of word | def stemmer(word):
"""Return leading consonants (if any), and 'stem' of word"""
word = word.lower()
pos = list(
filter(lambda v: v >= 0,
map(lambda c: word.index(c) if c in word else -1, 'aeiou')))
if pos:
first = min(pos)
return (word[:first], word[first:])
else:
return (word, '') |
test the stemmer | def test_stemmer():
"""test the stemmer"""
assert stemmer('') == ('', '')
assert stemmer('cake') == ('c', 'ake')
assert stemmer('chair') == ('ch', 'air')
assert stemmer('APPLE') == ('', 'apple')
assert stemmer('RDNZL') == ('rdnzl', '') |
Read the wordlist file | def read_wordlist(fh):
"""Read the wordlist file"""
return set(
flatten([line.lower().strip().split() for line in fh] if fh else [])) |
test | def test_read_wordlist():
"""test"""
assert read_wordlist(io.StringIO('foo\nbar\nfoo')) == set(['foo', 'bar'])
assert read_wordlist(io.StringIO('foo bar\nbar foo\nfoo')) == set(
['foo', 'bar']) |
exists | def test_exists():
"""exists"""
assert os.path.isfile(prg) |
usage | def test_usage():
"""usage"""
for flag in ['', '-h', '--help']:
out = getoutput(f'{prg} {flag}')
assert out.lower().startswith('usage') |
leading consonant | def test_take():
"""leading consonant"""
out = getoutput(f'{prg} take').splitlines()
assert len(out) == 56
assert out[0] == 'bake'
assert out[-1] == 'zake' |
consonant cluster | def test_chair():
"""consonant cluster"""
out = getoutput(f'{prg} chair').splitlines()
assert len(out) == 56
assert out[1] == 'blair'
assert out[-2] == 'yair' |
consonant cluster | def test_chair_uppercase():
"""consonant cluster"""
out = getoutput(f'{prg} CHAIR').splitlines()
assert len(out) == 56
assert out[1] == 'blair'
assert out[-2] == 'yair' |
leading vowel | def test_apple():
"""leading vowel"""
out = getoutput(f'{prg} apple').splitlines()
assert len(out) == 57
assert out[10] == 'flapple'
assert out[-10] == 'thwapple' |
no vowels | def test_no_vowels():
"""no vowels"""
consonants = 'bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ'
bad = ''.join(random.sample(consonants, k=random.randint(4, 10)))
out = getoutput(f'{prg} {bad}')
assert out == f'Cannot rhyme "{bad}"' |
Get command-line arguments | def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Southern fry text',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('text', metavar='text', help='Input text or file')
args = parser.parse_args()
if os.path.isfile(args.text):
args.text = open(args.text).read()
return args |
Make a jazz noise here | def main():
"""Make a jazz noise here"""
args = get_args()
for line in args.text.splitlines():
print(''.join(map(fry, re.split(r'(\W+)', line.rstrip())))) |
Drop the `g` from `-ing` words, change `you` to `y'all` | def fry(word):
"""Drop the `g` from `-ing` words, change `you` to `y'all`"""
ing_word = re.search('(.+)ing$', word)
you = re.match('([Yy])ou$', word)
if ing_word:
prefix = ing_word.group(1)
if re.search('[aeiouy]', prefix, re.IGNORECASE):
return prefix + "in'"
elif you:
return you.group(1) + "'all"
return word |
Test fry | def test_fry():
"""Test fry"""
assert fry('you') == "y'all"
assert fry('You') == "Y'all"
assert fry('your') == 'your'
assert fry('fishing') == "fishin'"
assert fry('Aching') == "Achin'"
assert fry('swing') == "swing" |
Get command-line arguments | def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Southern fry text',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('text', metavar='text', help='Input text or file')
args = parser.parse_args()
if os.path.isfile(args.text):
args.text = open(args.text).read()
return args |
Make a jazz noise here | def main():
"""Make a jazz noise here"""
args = get_args()
splitter = re.compile(r'(\W+)')
for line in args.text.splitlines():
print(''.join(map(fry, splitter.split(line.rstrip())))) |
Drop the `g` from `-ing` words, change `you` to `y'all` | def fry(word):
"""Drop the `g` from `-ing` words, change `you` to `y'all`"""
ing_word = re.search('(.+)ing$', word)
you = re.match('([Yy])ou$', word)
if ing_word:
prefix = ing_word.group(1)
if re.search('[aeiouy]', prefix, re.IGNORECASE):
return prefix + "in'"
elif you:
return you.group(1) + "'all"
return word |
Test fry | def test_fry():
"""Test fry"""
assert fry('you') == "y'all"
assert fry('You') == "Y'all"
assert fry('your') == 'your'
assert fry('fishing') == "fishin'"
assert fry('Aching') == "Achin'"
assert fry('swing') == "swing" |
Get command-line arguments | def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Southern fry text',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('text', metavar='text', help='Input text or file')
args = parser.parse_args()
if os.path.isfile(args.text):
args.text = open(args.text).read()
return args |
Make a jazz noise here | def main():
"""Make a jazz noise here"""
args = get_args()
for line in args.text.splitlines():
print(''.join(map(fry, re.split(r'(\W+)', line.rstrip())))) |
Drop the `g` from `-ing` words, change `you` to `y'all` | def fry(word):
"""Drop the `g` from `-ing` words, change `you` to `y'all`"""
if word.lower() == 'you':
return word[0] + "'all"
if word.endswith('ing'):
if any(map(lambda c: c.lower() in 'aeiouy', word[:-3])):
return word[:-1] + "'"
return word |
Test fry | def test_fry():
"""Test fry"""
assert fry('you') == "y'all"
assert fry('You') == "Y'all"
assert fry('your') == 'your'
assert fry('fishing') == "fishin'"
assert fry('Aching') == "Achin'"
assert fry('swing') == "swing" |
exists | def test_exists():
"""exists"""
assert os.path.isfile(prg) |
usage | def test_usage():
"""usage"""
for flag in ['-h', '--help']:
rv, out = getstatusoutput(f'{prg} {flag}')
assert rv == 0
assert re.match("usage", out, re.IGNORECASE) |
two-syllable ing words | def test_two_syllable_ing_words():
"""two-syllable ing words"""
tests = [("cooking", "cookin'"), ("Fishing", "Fishin'")]
for given, expected in tests:
out = getoutput(f'{prg} {given}')
assert out.strip() == expected.strip() |
one syllable ing words | def test_one_syllable_ing_words():
"""one syllable ing words"""
tests = [("sing", "sing"), ("Fling", "Fling")]
for given, expected in tests:
out = getoutput(f'{prg} {given}')
assert out.strip() == expected.strip() |
you/y'all | def test_you_yall():
"""you/y'all"""
tests = [("you", "y'all"), ("You", "Y'all")]
for given, expected in tests:
out = getoutput(f'{prg} {given}')
assert out.strip() == expected.strip() |
run with file | def run_file(file):
"""run with file"""
assert os.path.isfile(file)
expected_file = file + '.out'
assert os.path.isfile(expected_file)
expected = open(expected_file).read()
out = getoutput(f'{prg} {file}')
assert out.strip() == expected.strip() |
blake | def test_blake():
"""blake"""
run_file('inputs/blake.txt') |
banner | def test_banner():
"""banner"""
run_file('inputs/banner.txt') |
raven | def test_raven():
"""raven"""
run_file('inputs/raven.txt') |
dickinson | def test_dickinson():
"""dickinson"""
run_file('inputs/dickinson.txt') |
shakespeare | def test_shakespeare():
"""shakespeare"""
run_file('inputs/shakespeare.txt') |
Get command-line arguments | def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Scramble the letters of words',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('text', metavar='text', help='Input text or file')
parser.add_argument('-s',
'--seed',
help='Random seed',
metavar='seed',
type=int,
default=None)
args = parser.parse_args()
if os.path.isfile(args.text):
args.text = open(args.text).read().rstrip()
return args |
Make a jazz noise here | def main():
"""Make a jazz noise here"""
args = get_args()
random.seed(args.seed)
splitter = re.compile("([a-zA-Z](?:[a-zA-Z']*[a-zA-Z])?)")
for line in args.text.splitlines():
print(''.join(map(scramble, splitter.split(line)))) |
For words over 3 characters, shuffle the letters in the middle | def scramble(word):
"""For words over 3 characters, shuffle the letters in the middle"""
if len(word) > 3 and re.match(r'\w+', word):
middle = list(word[1:-1])
random.shuffle(middle)
word = word[0] + ''.join(middle) + word[-1]
return word |
Test scramble | def test_scramble():
"""Test scramble"""
state = random.getstate()
random.seed(1)
assert scramble("a") == "a"
assert scramble("ab") == "ab"
assert scramble("abc") == "abc"
assert scramble("abcd") == "acbd"
assert scramble("abcde") == "acbde"
assert scramble("abcdef") == "aecbdf"
assert scramble("abcde'f") == "abcd'ef"
random.setstate(state) |
exists | def test_exists():
"""exists"""
assert os.path.isfile(prg) |
usage | def test_usage():
"""usage"""
for flag in ['-h', '--help']:
rv, out = getstatusoutput(f'{prg} {flag}')
assert rv == 0
assert re.match("usage", out, re.IGNORECASE) |
Text | def test_text1():
"""Text"""
out = getoutput(f'{prg} foobar -s 1')
assert out.strip() == 'faobor' |
Text | def test_text2():
"""Text"""
text = 'The quick brown fox jumps over the lazy dog.'
expected = 'The qicuk bworn fox jpmus over the lzay dog.'
out = getoutput(f'{prg} "{text}" -s 2')
assert out.strip() == expected |
File input | def test_file_bustle():
"""File input"""
expected = """
The blutse in a hosue
The mrinong afetr daeth
Is seosnmelt of iinuetdrss
Etecand upon etrah,--
The sweenipg up the herat,
And pniuttg lvoe away
We slahl not want to use again
Unitl eettnriy.
""".strip()
out = getoutput(f'{prg} --seed 3 {bustle}')
assert out.strip() == expected.strip() |
File input | def test_file_fox():
"""File input"""
out = getoutput(f'{prg} --seed 4 {fox}')
assert out.strip() == 'The qciuk bworn fox jpums oevr the lzay dog.' |
File input | def test_file_spiders():
"""File input"""
out = getoutput(f'{prg} --seed 9 {spiders}')
expected = "Do'nt wrory, sedrpis,\nI keep hsoue\ncalusaly."
assert out.strip() == expected |
Get command-line arguments | def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Mad Libs',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('file',
metavar='FILE',
type=argparse.FileType('rt'),
help='Input file')
parser.add_argument('-i',
'--inputs',
help='Inputs (for testing)',
metavar='input',
type=str,
nargs='*')
return parser.parse_args() |
Make a jazz noise here | def main():
"""Make a jazz noise here"""
args = get_args()
inputs = args.inputs
text = args.file.read().rstrip()
blanks = re.findall('(<([^<>]+)>)', text)
if not blanks:
sys.exit(f'"{args.file.name}" has no placeholders.')
tmpl = 'Give me {} {}: '
for placeholder, pos in blanks:
article = 'an' if pos.lower()[0] in 'aeiou' else 'a'
answer = inputs.pop(0) if inputs else input(tmpl.format(article, pos))
text = re.sub(placeholder, answer, text, count=1)
print(text) |
Get command-line arguments | def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Mad Libs',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('file',
metavar='FILE',
type=argparse.FileType('rt'),
help='Input file')
parser.add_argument('-i',
'--inputs',
help='Inputs (for testing)',
metavar='str',
type=str,
nargs='*')
return parser.parse_args() |
Make a jazz noise here | def main():
"""Make a jazz noise here"""
args = get_args()
inputs = args.inputs
text = args.file.read().rstrip()
had_placeholders = False
tmpl = 'Give me {} {}: '
while True:
brackets = find_brackets(text)
if not brackets:
break
start, stop = brackets
placeholder = text[start:stop + 1]
pos = placeholder[1:-1]
article = 'an' if pos.lower()[0] in 'aeiou' else 'a'
answer = inputs.pop(0) if inputs else input(tmpl.format(article, pos))
text = text[0:start] + answer + text[stop + 1:]
had_placeholders = True
if had_placeholders:
print(text)
else:
sys.exit(f'"{args.file.name}" has no placeholders.') |
Find angle brackets | def find_brackets(text):
"""Find angle brackets"""
start = text.index('<') if '<' in text else -1
stop = text.index('>') if start >= 0 and '>' in text[start + 2:] else -1
return (start, stop) if start >= 0 and stop >= 0 else None |
Test for finding angle brackets | def test_find_brackets():
"""Test for finding angle brackets"""
assert find_brackets('') is None
assert find_brackets('<>') is None
assert find_brackets('<x>') == (0, 2)
assert find_brackets('foo <bar> baz') == (4, 8) |
exists | def test_exists():
"""exists"""
assert os.path.isfile(prg) |
usage | def test_usage():
"""usage"""
for flag in ['-h', '--help']:
rv, out = getstatusoutput(f'{prg} {flag}')
assert rv == 0
assert out.lower().startswith('usage') |
Test bad input file | def test_bad_file():
"""Test bad input file"""
bad = random_string()
rv, out = getstatusoutput(f'{prg} {bad}')
assert rv != 0
assert re.search(f"No such file or directory: '{bad}'", out) |
Test no blanks | def test_no_blanks():
"""Test no blanks"""
rv, out = getstatusoutput(f'{prg} {no_blanks}')
assert rv != 0
assert out == f'"{no_blanks}" has no placeholders.' |
test fox | def test_fox():
"""test fox"""
args = f'{fox} -i surly car under bicycle'
rv, out = getstatusoutput(f'{prg} {args}')
assert rv == 0
assert out.strip() == 'The quick surly car jumps under the lazy bicycle.' |
test help | def test_help():
"""test help"""
expected = """
Hey! I need tacos!
Oi! Not just salsa!
Hola! You know I need queso!
Arriba!
""".strip()
args = f'{hlp} -i Hey tacos Oi salsa Hola queso Arriba'
rv, out = getstatusoutput(f'{prg} {args}')
assert rv == 0
assert out.strip() == expected.strip() |
test verona | def test_verona():
"""test verona"""
expected = """
Two cars, both alike in dignity,
In fair Detroit, where we lay our scene,
From ancient oil break to new mutiny,
Where civil blood makes civil hands unclean.
From forth the fatal loins of these two foes
A pair of star-cross'd pistons take their life;
Whose misadventur'd piteous overthrows
Doth with their stick shift bury their parents' strife.
The fearful passage of their furious love,
And the continuance of their parents' rage,
Which, but their children's end, nought could accelerate,
Is now the 42 hours' traffic of our stage;
The which if you with patient foot attend,
What here shall hammer, our toil shall strive to mend.
""".strip()
args = (f'{verona} --inputs cars Detroit oil pistons '
'"stick shift" furious accelerate 42 foot hammer')
rv, out = getstatusoutput(f'{prg} {args}')
assert rv == 0
assert out.strip() == expected.strip() |
generate a random string | def random_string():
"""generate a random string"""
k = random.randint(5, 10)
return ''.join(random.choices(string.ascii_letters + string.digits, k=k)) |
Get command-line arguments | def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Make ASCII table',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-c',
'--cols',
help='Number of columns',
metavar='int',
type=int,
default=8)
parser.add_argument('-l',
'--lower',
help='Lower chr value',
metavar='int',
type=int,
default=0)
parser.add_argument('-u',
'--upper',
help='Upper chr value',
metavar='int',
type=int,
default=128)
args = parser.parse_args()
if args.lower < 0:
parser.error(f'--lower "{args.lower}" must be >= 0')
if args.upper > 128:
parser.error(f'--upper "{args.upper}" must be <= 128')
if args.lower > args.upper:
args.lower, args.upper = args.upper, args.lower
return args |
Make a jazz noise here | def main():
"""Make a jazz noise here"""
args = get_args()
lower = args.lower
upper = args.upper
num_cells = args.upper - args.lower
num_rows = round(num_cells / args.cols)
cells = list(chunker(list(map(cell, range(lower, upper))), num_rows))
df = pd.DataFrame(cells)
for i, row in df.T.iterrows():
print(' '.join(map(lambda v: v or ' ' * 5, row))) |
Format a cell | def cell(n):
"""Format a cell"""
return '{:3} {:5}'.format(
n, 'SPACE'
if n == 32 else 'DEL' if n == 127 else chr(n) if n >= 33 else 'NA') |
Chunk a list into bits | def chunker(seq, size):
"""Chunk a list into bits"""
return (seq[pos:pos + size] for pos in range(0, len(seq), size)) |
Get command-line arguments | def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Gematria',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('text', metavar='text', help='Input text or file')
args = parser.parse_args()
if os.path.isfile(args.text):
args.text = open(args.text).read().rstrip()
return args |
Make a jazz noise here | def main():
"""Make a jazz noise here"""
args = get_args()
for line in args.text.splitlines():
print(' '.join(map(word2num, line.split()))) |
Sum the ordinal values of all the characters | def word2num(word):
"""Sum the ordinal values of all the characters"""
return str(sum(map(ord, re.sub('[^A-Za-z0-9]', '', word)))) |
Test word2num | def test_word2num():
"""Test word2num"""
assert word2num("a") == "97"
assert word2num("abc") == "294"
assert word2num("ab'c") == "294"
assert word2num("4a-b'c,") == "346" |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.