response
stringlengths
1
33.1k
instruction
stringlengths
22
582k
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_text(): """Text""" out = getoutput(f'{prg} "foo bar baz"') assert out.strip() == '324 309 317'
File
def test_fox(): """File""" out = getoutput(f'{prg} {fox}') assert out.strip() == '289 541 552 333 559 444 321 448 314'
File
def test_spiders(): """File""" out = getoutput(f'{prg} {spiders}') assert out.strip() == '405 579 762\n73 421 548\n862'
File
def test_sonnet(): """File""" out = getoutput(f'{prg} {sonnet}') expected = """ 631 107 719 1132 402 215 834 444 771 307 435 438 73 313 527 632 230 771 545 275 765 400 631 444 230 875 534 275 437 450 656 307 546 230 416 729 210 421 227 322 435 422 215 428 816 421 318 421 318 444 747 985 821 440 431 327 307 433 431 538 412 436 73 451 549 964 537 306 215 537 886 656 656 966 510 73 542 221 422 307 431 230 545 389 227 321 426 213 517 213 318 749 404 659 532 548 559 213 746 417 295 341 552 438 1048 435 645 645 401 431 73 549 227 614 230 545 444 540 """.strip() assert out.strip() == expected
Get command-line arguments
def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Create Workout Of (the) Day (WOD)', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-f', '--file', help='CSV input file of exercises', metavar='FILE', type=argparse.FileType('rt'), default='inputs/exercises.csv') parser.add_argument('-s', '--seed', help='Random seed', metavar='seed', type=int, default=None) parser.add_argument('-n', '--num', help='Number of exercises', metavar='exercises', type=int, default=4) parser.add_argument('-e', '--easy', help='Halve the reps', action='store_true') args = parser.parse_args() if args.num < 1: parser.error(f'--num "{args.num}" must be greater than 0') return args
Make a jazz noise here
def main(): """Make a jazz noise here""" args = get_args() random.seed(args.seed) wod = [] exercises = read_csv(args.file) for name, low, high in random.sample(exercises, k=args.num): reps = random.randint(low, high) if args.easy: reps = int(reps / 2) wod.append((name, reps)) print(tabulate(wod, headers=('Exercise', 'Reps')))
Read the CSV input
def read_csv(fh): """Read the CSV input""" exercises = [] for row in csv.DictReader(fh, delimiter=','): low, high = map(int, row['reps'].split('-')) exercises.append((row['exercise'], low, high)) return exercises
Test read_csv
def test_read_csv(): """Test read_csv""" text = io.StringIO('exercise,reps\nBurpees,20-50\nSitups,40-100') assert read_csv(text) == [('Burpees', 20, 50), ('Situps', 40, 100)]
Get command-line arguments
def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Create Workout Of (the) Day (WOD)', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-f', '--file', help='CSV input file of exercises', metavar='FILE', type=argparse.FileType('rt'), default='inputs/exercises.csv') parser.add_argument('-s', '--seed', help='Random seed', metavar='seed', type=int, default=None) parser.add_argument('-n', '--num', help='Number of exercises', metavar='exercises', type=int, default=4) parser.add_argument('-e', '--easy', help='Halve the reps', action='store_true') args = parser.parse_args() if args.num < 1: parser.error(f'--num "{args.num}" must be greater than 0') return args
Make a jazz noise here
def main(): """Make a jazz noise here""" args = get_args() random.seed(args.seed) exercises = read_csv(args.file) if not exercises: sys.exit(f'No usable data in --file "{args.file.name}"') num_exercises = len(exercises) if args.num > num_exercises: sys.exit(f'--num "{args.num}" > exercises "{num_exercises}"') wod = [] for name, low, high in random.sample(exercises, k=args.num): reps = random.randint(low, high) if args.easy: reps = int(reps / 2) wod.append((name, reps)) print(tabulate(wod, headers=('Exercise', 'Reps')))
Read the CSV input
def read_csv(fh): """Read the CSV input""" exercises = [] for row in csv.DictReader(fh, delimiter=','): name, reps = row.get('exercise'), row.get('reps') if name and reps: match = re.match(r'(\d+)-(\d+)', reps) if match: low, high = map(int, match.groups()) exercises.append((name, low, high)) return exercises
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')
Dies on bad --num
def test_bad_num(): """Dies on bad --num""" bad = random.choice(range(-10, 0)) rv, out = getstatusoutput(f'{prg} -n {bad}') assert rv != 0 assert re.search(f'--num "{bad}" must be greater than 0', out)
Dies on bad file
def test_bad_file(): """Dies on bad file""" bad = random_string() rv, out = getstatusoutput(f'{prg} -f {bad}') assert rv != 0 assert re.search(f"No such file or directory: '{bad}'", out)
Runs OK
def test_seed1(): """Runs OK""" expected = """ Exercise Reps ---------- ------ Pushups 56 Situps 88 Crunches 27 Burpees 35 """ seed_flag = '-s' if random.choice([0, 1]) else '--seed' rv, out = getstatusoutput(f'{prg} {seed_flag} 1') assert rv == 0 assert out.strip() == expected.strip()
Runs OK
def test_seed1_easy(): """Runs OK""" expected = """ Exercise Reps ---------- ------ Pushups 28 Situps 44 Crunches 13 Burpees 17 """ seed_flag = '-s' if random.choice([0, 1]) else '--seed' easy_flag = '-e' if random.choice([0, 1]) else '--easy' rv, out = getstatusoutput(f'{prg} {easy_flag} {seed_flag} 1') assert rv == 0 assert out.strip() == expected.strip()
Runs OK
def test_seed2_num8(): """Runs OK""" expected = """ Exercise Reps ------------------ ------ Burpees 39 Situps 42 Crunches 29 Pushups 68 Plank 35 Hand-stand pushups 18 Pullups 30 Lunges 32 """ seed_flag = '-s' if random.choice([0, 1]) else '--seed' num_flag = '-n' if random.choice([0, 1]) else '--num' cmd = f'{prg} {num_flag} 8 {seed_flag} 2 -f {input1}' rv, out = getstatusoutput(cmd) assert rv == 0 assert out.strip() == expected.strip()
Runs OK
def test_seed4_num3_input2(): """Runs OK""" expected = """ Exercise Reps ----------------- ------ Hanging Chads 86 Red Barchettas 50 Squatting Chinups 35 """ seed_flag = '-s' if random.choice([0, 1]) else '--seed' num_flag = '-n' if random.choice([0, 1]) else '--num' rv, out = getstatusoutput(f'{prg} {num_flag} 3 {seed_flag} 4 -f {input2}') 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))
Test read_csv
def test_read_csv(): """Test read_csv""" good = io.StringIO('exercise,reps\nBurpees,20-50\nSitups,40-100') assert read_csv(good) == [('Burpees', 20, 50), ('Situps', 40, 100)] no_data = io.StringIO('') assert read_csv(no_data) == [] headers_only = io.StringIO('exercise,reps\n') assert read_csv(headers_only) == [] bad_headers = io.StringIO('Exercise,Reps\nBurpees,20-50\nSitups,40-100') assert read_csv(bad_headers) == [] bad_numbers = io.StringIO('exercise,reps\nBurpees,20-50\nSitups,forty-100') assert read_csv(bad_numbers) == [('Burpees', 20, 50)] no_dash = io.StringIO('exercise,reps\nBurpees,20\nSitups,40-100') assert read_csv(no_dash) == [('Situps', 40, 100)] tabs = io.StringIO('exercise\treps\nBurpees\t20-50\nSitups\t40-100') assert read_csv(tabs) == []
Get command-line arguments
def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Harvest parts of speech from texts', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('file', metavar='FILE', type=argparse.FileType('r'), nargs='+', help='Input file(s)') parser.add_argument('-o', '--outdir', help='Output directory', metavar='str', type=str, default='words') parser.add_argument('-l', '--limit', metavar='int', type=int, default=0, help='Limit to this many') return parser.parse_args()
Make a jazz noise here
def main(): """Make a jazz noise here""" args = get_args() out_dir = args.outdir if not os.path.isdir(out_dir): os.makedirs(out_dir) # Load English tokenizer, tagger, parser, NER and word vectors nlp = spacy.load("en_core_web_sm") nouns, adjs, verbs = Counter(), Counter(), Counter() for fh in args.file: doc = nlp(fh.read()) for token in doc: pos, word = token.pos_, token.lemma_.lower() if pos == 'NOUN': nouns.update([word]) elif pos == 'VERB': verbs.update([word]) elif pos == 'ADJ': adjs.update([word]) def limiter(words): return sorted(list(map(lambda t: t[0], words.most_common( args.limit)))) if args.limit else sorted(words) def write(words, name): if words: out_fh = open(os.path.join(out_dir, name), 'wt') out_fh.write('\n'.join(limiter(words)) + '\n') write(verbs, 'verbs.txt') write(nouns, 'nouns.txt') write(adjs, 'adjs.txt') print(f'Done, see output in "{out_dir}".')
Get command-line arguments
def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Password maker', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('file', metavar='FILE', type=argparse.FileType('rt'), nargs='+', help='Input file(s)') parser.add_argument('-n', '--num', metavar='num_passwords', type=int, default=3, help='Number of passwords to generate') parser.add_argument('-w', '--num_words', metavar='num_words', type=int, default=4, help='Number of words to use for password') parser.add_argument('-m', '--min_word_len', metavar='minimum', type=int, default=3, help='Minimum word length') parser.add_argument('-x', '--max_word_len', metavar='maximum', type=int, default=6, help='Maximum word length') parser.add_argument('-s', '--seed', metavar='seed', type=int, help='Random seed') parser.add_argument('-l', '--l33t', action='store_true', help='Obfuscate letters') return parser.parse_args()
Remove non-word characters from word
def clean(word): """Remove non-word characters from word""" return re.sub('[^a-zA-Z]', '', word)
l33t
def l33t(text): """l33t""" text = ransom(text) xform = str.maketrans({ 'a': '@', 'A': '4', 'O': '0', 't': '+', 'E': '3', 'I': '1', 'S': '5' }) return text.translate(xform) + random.choice(string.punctuation)
Randomly choose an upper or lowercase letter to return
def ransom(text): """Randomly choose an upper or lowercase letter to return""" return ''.join( map(lambda c: c.upper() if random.choice([0, 1]) else c.lower(), text))
exists
def test_exists(): """exists""" assert os.path.isfile(prg) assert os.path.isfile(words)
usage
def test_usage(): """usage""" for flag in ['-h', '--help']: rv, out = getstatusoutput(f'{prg} {flag}') assert rv == 0 assert out.lower().startswith('usage')
Dies on bad file
def test_bad_file(): """Dies on bad file""" bad = random_string() rv, out = getstatusoutput(f'{prg} {bad}') assert rv != 0 assert re.search(f"No such file or directory: '{bad}'", out)
Dies on bad num
def test_bad_num(): """Dies on bad num""" bad = random_string() flag = '-n' if random.choice([0, 1]) else '--num' rv, out = getstatusoutput(f'{prg} {flag} {bad} {words}') assert rv != 0 assert re.search(f"invalid int value: '{bad}'", out)
Dies on bad num
def test_bad_num_words(): """Dies on bad num""" bad = random_string() flag = '-w' if random.choice([0, 1]) else '--num_words' rv, out = getstatusoutput(f'{prg} {flag} {bad} {words}') assert rv != 0 assert re.search(f"invalid int value: '{bad}'", out)
Dies on bad min_word_len
def test_bad_min_word_len(): """Dies on bad min_word_len""" bad = random_string() flag = '-m' if random.choice([0, 1]) else '--min_word_len' rv, out = getstatusoutput(f'{prg} {flag} {bad} {words}') assert rv != 0 assert re.search(f"invalid int value: '{bad}'", out)
Dies on bad max_word_len
def test_bad_max_word_len(): """Dies on bad max_word_len""" bad = random_string() flag = '-m' if random.choice([0, 1]) else '--max_word_len' rv, out = getstatusoutput(f'{prg} {flag} {bad} {words}') assert rv != 0 assert re.search(f"invalid int value: '{bad}'", out)
Dies on bad seed
def test_bad_seed(): """Dies on bad seed""" bad = random_string() flag = '-s' if random.choice([0, 1]) else '--seed' rv, out = getstatusoutput(f'{prg} {flag} {bad} {words}') assert rv != 0 assert re.search(f"invalid int value: '{bad}'", out)
Test
def test_defaults(): """Test""" rv, out = getstatusoutput(f'{prg} -s 1 {words}') assert rv == 0 assert out.strip() == '\n'.join([ 'DuniteBoonLociDefat', 'WegaTitmalUnplatSatire', 'IdeanClipsVitiArriet' ])
Test
def test_num(): """Test""" rv, out = getstatusoutput(f'{prg} -s 1 -n 1 {words}') assert rv == 0 assert out.strip() == 'DuniteBoonLociDefat'
Test
def test_num_words(): """Test""" rv, out = getstatusoutput(f'{prg} -s 1 -w 2 {words}') assert rv == 0 assert out.strip() == '\n'.join(['DuniteBoon', 'LociDefat', 'WegaTitmal'])
Test
def test_min_word_len(): """Test""" rv, out = getstatusoutput(f'{prg} -s 1 -m 5 {words}') assert rv == 0 assert out.strip() == '\n'.join([ 'CarneyRapperWabenoUndine', 'BabaiFarerBugleOnlepy', 'UnbittMinnyNatalSkanda' ])
Test
def test_max_word_len(): """Test""" rv, out = getstatusoutput(f'{prg} -s 1 -x 10 {words}') assert rv == 0 assert out.strip() == '\n'.join([ 'DicemanYardwandBoeberaKismetic', 'CubiculumTilsitSnowcapSuer', 'ProhasteHaddockChristmasyTenonitis' ])
Test
def test_l33t(): """Test""" rv, out = getstatusoutput(f'{prg} -s 1 -l {words}') assert rv == 0 assert out.strip() == '\n'.join([ 'DUn1Teb0onloCiDef4T/', 'Weg4TiTm@LuNPl4T54+1r3_', 'iD3@Ncl1P5v1+14rrie+/' ])
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))
Test clean
def test_clean(): """Test clean""" assert clean('') == '' assert clean("states,") == 'states' assert clean("Don't") == 'Dont'
Test ransom
def test_ransom(): """Test ransom""" state = random.getstate() random.seed(1) assert (ransom('Money') == 'moNeY') assert (ransom('Dollars') == 'DOLlaRs') random.setstate(state)
Test l33t
def test_l33t(): """Test l33t""" state = random.getstate() random.seed(1) assert l33t('Money') == 'moNeY{' assert l33t('Dollars') == 'D0ll4r5`' random.setstate(state)
Get command-line arguments
def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Tic-Tac-Toe', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-b', '--board', help='The state of the board', metavar='board', type=str, default='.' * 9) parser.add_argument('-p', '--player', help='Player', choices='XO', metavar='player', type=str, default=None) parser.add_argument('-c', '--cell', help='Cell 1-9', metavar='cell', type=int, choices=range(1, 10), default=None) args = parser.parse_args() if any([args.player, args.cell]) and not all([args.player, args.cell]): parser.error('Must provide both --player and --cell') if not re.search('^[.XO]{9}$', args.board): parser.error(f'--board "{args.board}" must be 9 characters of ., X, O') if args.player and args.cell and args.board[args.cell - 1] in 'XO': parser.error(f'--cell "{args.cell}" already taken') return args
Make a jazz noise here
def main(): """Make a jazz noise here""" args = get_args() board = list(args.board) if args.player and args.cell: board[args.cell - 1] = args.player print(format_board(board)) winner = find_winner(board) print(f'{winner} has won!' if winner else 'No winner.')
Format the board
def format_board(board): """Format the board""" cells = [str(i) if c == '.' else c for i, c in enumerate(board, start=1)] bar = '-------------' cells_tmpl = '| {} | {} | {} |' return '\n'.join([ bar, cells_tmpl.format(*cells[:3]), bar, cells_tmpl.format(*cells[3:6]), bar, cells_tmpl.format(*cells[6:]), bar ])
Return the winner
def find_winner(board): """Return the winner""" winning = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]] for player in ['X', 'O']: for i, j, k in winning: combo = [board[i], board[j], board[k]] if combo == [player, player, player]: return player
Get command-line arguments
def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Tic-Tac-Toe', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-b', '--board', help='The state of the board', metavar='board', type=str, default='.' * 9) parser.add_argument('-p', '--player', help='Player', choices='XO', metavar='player', type=str, default=None) parser.add_argument('-c', '--cell', help='Cell 1-9', metavar='cell', type=int, choices=range(1, 10), default=None) args = parser.parse_args() if any([args.player, args.cell]) and not all([args.player, args.cell]): parser.error('Must provide both --player and --cell') if not re.search('^[.XO]{9}$', args.board): parser.error(f'--board "{args.board}" must be 9 characters of ., X, O') if args.player and args.cell and args.board[args.cell - 1] in 'XO': parser.error(f'--cell "{args.cell}" already taken') return args
Make a jazz noise here
def main(): """Make a jazz noise here""" args = get_args() board = list(args.board) if args.player and args.cell: board[args.cell - 1] = args.player print(format_board(board)) winner = find_winner(board) print(f'{winner} has won!' if winner else 'No winner.')
Format the board
def format_board(board): """Format the board""" cells = [] for i, char in enumerate(board, start=1): cells.append(str(i) if char == '.' else char) bar = '-------------' cells_tmpl = '| {} | {} | {} |' return '\n'.join([ bar, cells_tmpl.format(cells[0], cells[1], cells[2]), bar, cells_tmpl.format(cells[3], cells[4], cells[5]), bar, cells_tmpl.format(cells[6], cells[7], cells[8]), bar ])
Return the winner
def find_winner(board): """Return the winner""" winning = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]] for combo in winning: group = list(map(lambda i: board[i], combo)) for player in ['X', 'O']: if all(x == player for x in group): return player
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')
makes board on no input
def test_no_input(): """makes board on no input""" board = """ ------------- | 1 | 2 | 3 | ------------- | 4 | 5 | 6 | ------------- | 7 | 8 | 9 | ------------- No winner. """.strip() rv, out = getstatusoutput(prg) assert rv == 0 assert out.strip() == board
dies on bad board
def test_bad_board(): """dies on bad board""" expected = '--board "{}" must be 9 characters of ., X, O' for bad in ['ABC', '...XXX', 'XXXOOOXX']: rv, out = getstatusoutput(f'{prg} --board {bad}') assert rv != 0 assert re.search(expected.format(bad), out)
dies on bad player
def test_bad_player(): """dies on bad player""" bad = random.choice([c for c in string.ascii_uppercase if c not in 'XO']) rv, out = getstatusoutput(f'{prg} -p {bad}') assert rv != 0 expected = f"-p/--player: invalid choice: '{bad}'" assert re.search(expected, out)
dies on bad cell
def test_bad_cell_int(): """dies on bad cell""" for bad in [0, 10]: rv, out = getstatusoutput(f'{prg} --cell {bad}') assert rv != 0 assert re.search(f'-c/--cell: invalid choice: {bad}', out)
dies on bad cell string value
def test_bad_cell_str(): """dies on bad cell string value""" bad = random.choice(string.ascii_letters) rv, out = getstatusoutput(f'{prg} --cell {bad}') assert rv != 0 assert re.search(f"-c/--cell: invalid int value: '{bad}'", out, re.I)
test for both --player and --cell
def test_both_player_and_cell(): """test for both --player and --cell""" player = random.choice('XO') rv, out = getstatusoutput(f'{prg} --player {player}') assert rv != 0 assert re.search('Must provide both --player and --cell', out)
makes board on good input
def test_good_board_01(): """makes board on good input""" board = """ ------------- | 1 | 2 | 3 | ------------- | 4 | 5 | 6 | ------------- | 7 | 8 | 9 | ------------- No winner. """.strip() rv, out = getstatusoutput(f'{prg} -b .........') assert rv == 0 assert out.strip() == board
makes board on good input
def test_good_board_02(): """makes board on good input""" board = """ ------------- | 1 | 2 | 3 | ------------- | O | X | X | ------------- | 7 | 8 | 9 | ------------- No winner. """.strip() rv, out = getstatusoutput(f'{prg} --board ...OXX...') assert rv == 0 assert out.strip() == board
mutates board on good input
def test_mutate_board_01(): """mutates board on good input""" board = """ ------------- | X | 2 | 3 | ------------- | 4 | 5 | 6 | ------------- | 7 | 8 | 9 | ------------- No winner. """.strip() rv, out = getstatusoutput(f'{prg} -b ......... --player X -c 1') assert rv == 0 assert out.strip() == board
mutates board on good input
def test_mutate_board_02(): """mutates board on good input""" board = """ ------------- | X | X | O | ------------- | 4 | O | 6 | ------------- | O | O | X | ------------- O has won! """.strip() rv, out = getstatusoutput(f'{prg} --board XXO...OOX --p O -c 5') assert rv == 0 assert out.strip() == board
test for a cell already taken
def test_mutate_cell_taken(): """test for a cell already taken""" rv1, out1 = getstatusoutput(f'{prg} -b XXO...OOX --player X --cell 9') assert rv1 != 0 assert re.search('--cell "9" already taken', out1) rv2, out2 = getstatusoutput(f'{prg} --board XXO...OOX --p O -c 1') assert rv2 != 0 assert re.search('--cell "1" already taken', out2)
test winning boards
def test_winning(): """test winning boards""" wins = [('PPP......'), ('...PPP...'), ('......PPP'), ('P..P..P..'), ('.P..P..P.'), ('..P..P..P'), ('P...P...P'), ('..P.P.P..')] for player in 'XO': other_player = 'O' if player == 'X' else 'X' for board in wins: board = board.replace('P', player) dots = [i for i in range(len(board)) if board[i] == '.'] mut = random.sample(dots, k=2) test_board = ''.join([ other_player if i in mut else board[i] for i in range(len(board)) ]) out = getoutput(f'{prg} -b {test_board}').splitlines() assert out[-1].strip() == f'{player} has won!'
test losing boards
def test_losing(): """test losing boards""" losing_board = list('XXOO.....') for i in range(10): random.shuffle(losing_board) out = getoutput(f'{prg} -b {"".join(losing_board)}').splitlines() assert out[-1].strip() == 'No winner.'
makes default board
def test_board_no_board(): """makes default board""" board = """ ------------- | 1 | 2 | 3 | ------------- | 4 | 5 | 6 | ------------- | 7 | 8 | 9 | ------------- """.strip() assert format_board('.' * 9) == board
makes board
def test_board_with_board(): """makes board""" board = """ ------------- | 1 | 2 | 3 | ------------- | O | X | X | ------------- | 7 | 8 | 9 | ------------- """.strip() assert format_board('...OXX...') == board
test winning boards
def test_winning(): """test winning boards""" wins = [('PPP......'), ('...PPP...'), ('......PPP'), ('P..P..P..'), ('.P..P..P.'), ('..P..P..P'), ('P...P...P'), ('..P.P.P..')] for player in 'XO': other_player = 'O' if player == 'X' else 'X' for board in wins: board = board.replace('P', player) dots = [i for i in range(len(board)) if board[i] == '.'] mut = random.sample(dots, k=2) test_board = ''.join([ other_player if i in mut else board[i] for i in range(len(board)) ]) assert find_winner(test_board) == player
test losing boards
def test_losing(): """test losing boards""" losing_board = list('XXOO.....') for _ in range(10): random.shuffle(losing_board) assert find_winner(''.join(losing_board)) is None
Make a jazz noise here
def main() -> None: """Make a jazz noise here""" state = State() while True: print("\033[H\033[J") print(format_board(state.board)) if state.error: print(state.error) elif state.winner: print(f'{state.winner} has won!') break elif state.quit: print('You lose, loser!') break elif state.draw: print("All right, we'll call it a draw.") break state = get_move(state)
Get the player's move
def get_move(state: State) -> State: """Get the player's move""" player = state.player cell = input(f'Player {player}, what is your move? [q to quit]: ') if cell == 'q': return state._replace(quit=True) if not (cell.isdigit() and int(cell) in range(1, 10)): return state._replace(error=f'Invalid cell "{cell}", please use 1-9') cell_num = int(cell) if state.board[cell_num - 1] in 'XO': return state._replace(error=f'Cell "{cell}" already taken') board = state.board board[cell_num - 1] = player return state._replace(board=board, player='O' if player == 'X' else 'X', winner=find_winner(board), draw='.' not in board, error=None)
Format the board
def format_board(board: List[str]) -> str: """Format the board""" cells = [str(i) if c == '.' else c for i, c in enumerate(board, 1)] bar = '-------------' cells_tmpl = '| {} | {} | {} |' return '\n'.join([ bar, cells_tmpl.format(*cells[:3]), bar, cells_tmpl.format(*cells[3:6]), bar, cells_tmpl.format(*cells[6:]), bar ])
Return the winner
def find_winner(board: List[str]) -> Optional[str]: """Return the winner""" winning = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]] for player in ['X', 'O']: for i, j, k in winning: combo = [board[i], board[j], board[k]] if combo == [player, player, player]: return player return None
Make a jazz noise here
def main() -> None: """Make a jazz noise here""" state = State(board='.' * 9, player='X', quit=False, draw=False, error=None, winner=None) while True: print("\033[H\033[J") print(format_board(state['board'])) if state['error']: print(state['error']) elif state['winner']: print(f"{state['winner']} has won!") break elif state['quit']: print('You lose, loser!') break elif state['draw']: print('No winner.') break state = get_move(state)
Get the player's move
def get_move(state: State) -> State: """Get the player's move""" player = state['player'] cell = input(f'Player {player}, what is your move? [q to quit]: ') if cell == 'q': state['quit'] = True return state if not (cell.isdigit() and int(cell) in range(1, 10)): state['error'] = f'Invalid cell "{cell}", please use 1-9' return state cell_num = int(cell) if state['board'][cell_num - 1] in 'XO': state['error'] = f'Cell "{cell}" already taken' return state board = list(state['board']) board[cell_num - 1] = player return State( board=''.join(board), player='O' if player == 'X' else 'X', winner=find_winner(board), draw='.' not in board, error=None, quit=False, )
Format the board
def format_board(board: str) -> str: """Format the board""" cells = [str(i) if c == '.' else c for i, c in enumerate(board, 1)] bar = '-------------' cells_tmpl = '| {} | {} | {} |' return '\n'.join([ bar, cells_tmpl.format(*cells[:3]), bar, cells_tmpl.format(*cells[3:6]), bar, cells_tmpl.format(*cells[6:]), bar ])
Return the winner
def find_winner(board: List[str]) -> Optional[str]: """Return the winner""" winning = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]] for player in ['X', 'O']: for i, j, k in winning: combo = [board[i], board[j], board[k]] if combo == [player, player, player]: return player return None
makes default board
def test_board_no_state(): """makes default board""" board = """ ------------- | 1 | 2 | 3 | ------------- | 4 | 5 | 6 | ------------- | 7 | 8 | 9 | ------------- """.strip() assert format_board('.' * 9) == board
makes board
def test_board_with_state(): """makes board""" board = """ ------------- | 1 | 2 | 3 | ------------- | O | X | X | ------------- | 7 | 8 | 9 | ------------- """.strip() assert format_board('...OXX...') == board
test winning states
def test_winning(): """test winning states""" wins = [('PPP......'), ('...PPP...'), ('......PPP'), ('P..P..P..'), ('.P..P..P.'), ('..P..P..P'), ('P...P...P'), ('..P.P.P..')] for player in 'XO': other_player = 'O' if player == 'X' else 'X' for state in wins: state = state.replace('P', player) dots = [i for i in range(len(state)) if state[i] == '.'] mut = random.sample(dots, k=2) test_state = ''.join([ other_player if i in mut else state[i] for i in range(len(state)) ]) assert find_winner(test_state) == player
test losing states
def test_losing(): """test losing states""" losing_state = list('XXOO.....') for i in range(10): random.shuffle(losing_state) assert find_winner(''.join(losing_state)) == None
Get command-line arguments
def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Python version of `cat -n`', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('file', metavar='FILE', type=argparse.FileType('rt'), help='Input file') return parser.parse_args()
Make a jazz noise here
def main(): """Make a jazz noise here""" args = get_args() for i, line in enumerate(args.file, start=1): print(f'{i:6} {line}', end='')
Get command-line arguments
def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Python version of `cat -n`', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('file', metavar='str', type=str, help='Input file') args = parser.parse_args() if not os.path.isfile(args.file): parser.error(f'"{args.file}" is not a file') args.file = open(args.file) return args
Make a jazz noise here
def main(): """Make a jazz noise here""" args = get_args() for i, line in enumerate(args.file, start=1): print(f'{i:6} {line}', end='')
get args
def get_args(): """get args""" parser = argparse.ArgumentParser( description='Choices', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('color', metavar='color', help='Color', choices=['red', 'yellow', 'blue']) parser.add_argument('size', metavar='size', type=int, choices=range(1, 11), help='The size of the garment') return parser.parse_args()
main
def main(): """main""" args = get_args() print('color =', args.color) print('size =', args.size)
Get command-line arguments
def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='Manually check an argument', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-v', '--val', help='Integer value between 1 and 10', metavar='int', type=int, default=5) args = parser.parse_args() # <1> if not 1 <= args.val <= 10: # <2> parser.error(f'--val "{args.val}" must be between 1 and 10') # <3> return args
Make a jazz noise here
def main(): """Make a jazz noise here""" args = get_args() print(f'val = "{args.val}"')
get args
def get_args(): """get args""" parser = argparse.ArgumentParser( description='nargs=+', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('numbers', metavar='int', nargs='+', type=int, help='Numbers') return parser.parse_args()
main
def main(): """main""" args = get_args() numbers = args.numbers print('{} = {}'.format(' + '.join(map(str, numbers)), sum(numbers)))
get args
def get_args(): """get args""" parser = argparse.ArgumentParser( description='nargs=2', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('numbers', metavar='int', nargs=2, type=int, help='Numbers') return parser.parse_args()
main
def main(): """main""" args = get_args() n1, n2 = args.numbers print(f'{n1} + {n2} = {n1 + n2}')
Get command-line arguments
def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( description='A single positional argument', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('name', metavar='name', help='The name to greet') return parser.parse_args()
Make a jazz noise here
def main(): """Make a jazz noise here""" args = get_args() print('Hello, ' + args.name + '!')