diff --git a/01_hello/hello04_argparse_positional.py b/01_hello/hello04_argparse_positional.py index 5d9a5e921..fcc607fd5 100755 --- a/01_hello/hello04_argparse_positional.py +++ b/01_hello/hello04_argparse_positional.py @@ -6,4 +6,4 @@ parser = argparse.ArgumentParser(description='Say hello') parser.add_argument('name', help='Name to greet') args = parser.parse_args() -print('Hello, ' + args.name + '!') +print(f'Hello, {args.name}!') diff --git a/01_hello/hello05_argparse_option.py b/01_hello/hello05_argparse_option.py index e87a8d787..29b9fdac7 100755 --- a/01_hello/hello05_argparse_option.py +++ b/01_hello/hello05_argparse_option.py @@ -7,4 +7,4 @@ parser.add_argument('-n', '--name', metavar='name', default='World', help='Name to greet') args = parser.parse_args() -print('Hello, ' + args.name + '!') +print(f'Hello, {args.name}!') diff --git a/01_hello/hello06_main_function.py b/01_hello/hello06_main_function.py index 9170ef31a..b17136f28 100755 --- a/01_hello/hello06_main_function.py +++ b/01_hello/hello06_main_function.py @@ -8,7 +8,7 @@ def main(): parser.add_argument('-n', '--name', metavar='name', default='World', help='Name to greet') args = parser.parse_args() - print('Hello, ' + args.name + '!') + print(f'Hello, {args.name}!') if __name__ == '__main__': main() diff --git a/01_hello/hello07_get_args.py b/01_hello/hello07_get_args.py index 9a6cb9389..b2e2200c3 100755 --- a/01_hello/hello07_get_args.py +++ b/01_hello/hello07_get_args.py @@ -11,7 +11,7 @@ def get_args(): def main(): args = get_args() - print('Hello, ' + args.name + '!') + print(f'Hello, {args.name}!') if __name__ == '__main__': main() diff --git a/01_hello/hello08_formatted.py b/01_hello/hello08_formatted.py index e35e5d3b5..9446ac7a5 100755 --- a/01_hello/hello08_formatted.py +++ b/01_hello/hello08_formatted.py @@ -21,7 +21,7 @@ def main(): """Make a jazz noise here""" args = get_args() - print('Hello, ' + args.name + '!') + print(f'Hello, {args.name}!') # -------------------------------------------------- diff --git a/03_picnic/solution.py b/03_picnic/solution.py index 4ccc500fb..ffe5873ae 100755 --- a/03_picnic/solution.py +++ b/03_picnic/solution.py @@ -42,7 +42,7 @@ def main(): elif num == 2: bringing = ' and '.join(items) else: - items[-1] = 'and ' + items[-1] + items[-1] = f'and {items[-1]}' bringing = ', '.join(items) print('You are bringing {}.'.format(bringing)) diff --git a/04_jump_the_five/solution2.py b/04_jump_the_five/solution2.py index 5c2ec7623..8982ac42f 100755 --- a/04_jump_the_five/solution2.py +++ b/04_jump_the_five/solution2.py @@ -26,9 +26,7 @@ def main(): '6': '4', '7': '3', '8': '2', '9': '1', '0': '5'} # Method 2: for loop to build new string - new_text = '' - for char in args.text: - new_text += jumper.get(char, char) + new_text = ''.join(jumper.get(char, char) for char in args.text) print(new_text) diff --git a/04_jump_the_five/solution3.py b/04_jump_the_five/solution3.py index 836aa59b4..df65cbbed 100755 --- a/04_jump_the_five/solution3.py +++ b/04_jump_the_five/solution3.py @@ -26,9 +26,7 @@ def main(): '6': '4', '7': '3', '8': '2', '9': '1', '0': '5'} # Method 3: for loop to build new list - new_text = [] - for char in args.text: - new_text.append(jumper.get(char, char)) + new_text = [jumper.get(char, char) for char in args.text] print(''.join(new_text)) diff --git a/07_gashlycrumb/solution1.py b/07_gashlycrumb/solution1.py index 91c87fca5..76471bde4 100755 --- a/07_gashlycrumb/solution1.py +++ b/07_gashlycrumb/solution1.py @@ -34,10 +34,7 @@ def main(): args = get_args() - lookup = {} - for line in args.file: - lookup[line[0].upper()] = line.rstrip() - + lookup = {line[0].upper(): line.rstrip() for line in args.file} for letter in args.letter: if letter.upper() in lookup: print(lookup[letter.upper()]) diff --git a/11_bottles_of_beer/solution.py b/11_bottles_of_beer/solution.py index f01836d36..9f60e202f 100755 --- a/11_bottles_of_beer/solution.py +++ b/11_bottles_of_beer/solution.py @@ -43,12 +43,14 @@ def verse(bottle): s1 = '' if bottle == 1 else 's' s2 = '' if next_bottle == 1 else 's' num_next = 'No more' if next_bottle == 0 else next_bottle - return '\n'.join([ - f'{bottle} bottle{s1} of beer on the wall,', - f'{bottle} bottle{s1} of beer,', - f'Take one down, pass it around,', - f'{num_next} bottle{s2} of beer on the wall!', - ]) + return '\n'.join( + [ + f'{bottle} bottle{s1} of beer on the wall,', + f'{bottle} bottle{s1} of beer,', + 'Take one down, pass it around,', + f'{num_next} bottle{s2} of beer on the wall!', + ] + ) # -------------------------------------------------- diff --git a/12_ransom/solution1_for_loop.py b/12_ransom/solution1_for_loop.py index 87155b26a..68d33be41 100755 --- a/12_ransom/solution1_for_loop.py +++ b/12_ransom/solution1_for_loop.py @@ -39,10 +39,7 @@ def main(): random.seed(args.seed) # Method 1: Iterate each character, add to list - ransom = [] - for char in args.text: - ransom.append(choose(char)) - + ransom = [choose(char) for char in args.text] print(''.join(ransom)) diff --git a/12_ransom/solution3_for_append_string.py b/12_ransom/solution3_for_append_string.py index e76ebf4b2..9b79fda6d 100755 --- a/12_ransom/solution3_for_append_string.py +++ b/12_ransom/solution3_for_append_string.py @@ -39,10 +39,7 @@ def main(): random.seed(args.seed) # Method 3: Iterate each character, add to a str - ransom = '' - for char in args.text: - ransom += choose(char) - + ransom = ''.join(choose(char) for char in args.text) print(''.join(ransom)) diff --git a/13_twelve_days/solution.py b/13_twelve_days/solution.py index 5b82227fe..8226f28ae 100755 --- a/13_twelve_days/solution.py +++ b/13_twelve_days/solution.py @@ -76,7 +76,7 @@ def verse(day): lines.extend(reversed(gifts[:day])) if day > 1: - lines[-1] = 'And ' + lines[-1].lower() + lines[-1] = f'And {lines[-1].lower()}' return '\n'.join(lines) diff --git a/13_twelve_days/solution_emoji.py b/13_twelve_days/solution_emoji.py index 3c7ea0a16..3773e3c91 100755 --- a/13_twelve_days/solution_emoji.py +++ b/13_twelve_days/solution_emoji.py @@ -77,7 +77,7 @@ def verse(day): lines.extend(reversed(gifts[:day])) if day > 1: - lines[-1] = 'And ' + lines[-1].lower() + lines[-1] = f'And {lines[-1].lower()}' return '\n'.join(lines) diff --git a/13_twelve_days/test.py b/13_twelve_days/test.py index b7fdb9836..a68f5a1cf 100755 --- a/13_twelve_days/test.py +++ b/13_twelve_days/test.py @@ -98,7 +98,7 @@ def test_all(): os.remove(out_file) try: - out = getoutput(cmd + f' -o {out_file}').rstrip() + out = getoutput(f'{cmd} -o {out_file}').rstrip() assert out == '' assert os.path.isfile(out_file) output = open(out_file).read().rstrip() diff --git a/14_rhymer/solution1_regex.py b/14_rhymer/solution1_regex.py index df826eec4..7a1a39413 100755 --- a/14_rhymer/solution1_regex.py +++ b/14_rhymer/solution1_regex.py @@ -44,21 +44,17 @@ def stemmer(word): 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}' + ']+)?' # capture one or more, optional + '([') + vowels) + '])' # capture at least one vowel + '(.*)') 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: + if not (match := re.match(pattern, word)): return (word, '') + p1 = match.group(1) or '' + p2 = match.group(2) or '' + p3 = match.group(3) or '' + return (p1, p2 + p3) # -------------------------------------------------- diff --git a/14_rhymer/solution2_no_regex.py b/14_rhymer/solution2_no_regex.py index 7e6fa8af1..f359e9bee 100755 --- a/14_rhymer/solution2_no_regex.py +++ b/14_rhymer/solution2_no_regex.py @@ -39,9 +39,9 @@ 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: + if vowel_pos := list( + map(word.index, filter(lambda v: v in word, 'aeiou')) + ): first_vowel = min(vowel_pos) return (word[:first_vowel], word[first_vowel:]) else: diff --git a/15_kentucky_friar/solution3_no_regex.py b/15_kentucky_friar/solution3_no_regex.py index e530728f7..29ba4365d 100755 --- a/15_kentucky_friar/solution3_no_regex.py +++ b/15_kentucky_friar/solution3_no_regex.py @@ -41,9 +41,10 @@ def fry(word): 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] + "'" + if word.endswith('ing') and any( + map(lambda c: c.lower() in 'aeiouy', word[:-3]) + ): + return word[:-1] + "'" return word diff --git a/15_kentucky_friar/test.py b/15_kentucky_friar/test.py index cc1ae9a49..6b7dc88f2 100755 --- a/15_kentucky_friar/test.py +++ b/15_kentucky_friar/test.py @@ -60,7 +60,7 @@ def run_file(file): """run with file""" assert os.path.isfile(file) - expected_file = file + '.out' + expected_file = f'{file}.out' assert os.path.isfile(expected_file) expected = open(expected_file).read() diff --git a/17_mad_libs/solution2_no_regex.py b/17_mad_libs/solution2_no_regex.py index 27b1195d9..b1403f56b 100755 --- a/17_mad_libs/solution2_no_regex.py +++ b/17_mad_libs/solution2_no_regex.py @@ -48,7 +48,7 @@ def main(): 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:] + text = text[:start] + answer + text[stop + 1:] had_placeholders = True if had_placeholders: diff --git a/19_wod/solution2.py b/19_wod/solution2.py index a4c8e55fc..96d0a05e1 100755 --- a/19_wod/solution2.py +++ b/19_wod/solution2.py @@ -85,8 +85,7 @@ def read_csv(fh): 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: + if match := re.match(r'(\d+)-(\d+)', reps): low, high = map(int, match.groups()) exercises.append((name, low, high)) diff --git a/19_wod/using_csv1.py b/19_wod/using_csv1.py index bb90a21c0..55e7f329b 100755 --- a/19_wod/using_csv1.py +++ b/19_wod/using_csv1.py @@ -5,8 +5,5 @@ with open('inputs/exercises.csv') as fh: reader = csv.DictReader(fh, delimiter=',') - records = [] - for rec in reader: - records.append(rec) - + records = list(reader) pprint(records) diff --git a/21_tictactoe/solution2.py b/21_tictactoe/solution2.py index 913cfeb39..b0e793489 100755 --- a/21_tictactoe/solution2.py +++ b/21_tictactoe/solution2.py @@ -69,9 +69,10 @@ def main(): def format_board(board): """Format the board""" - cells = [] - for i, char in enumerate(board, start=1): - cells.append(str(i) if char == '.' else char) + cells = [ + str(i) if char == '.' else char + for i, char in enumerate(board, start=1) + ] bar = '-------------' cells_tmpl = '| {} | {} | {} |' diff --git a/21_tictactoe/test.py b/21_tictactoe/test.py index 5c63bf9ab..a5663ddb7 100755 --- a/21_tictactoe/test.py +++ b/21_tictactoe/test.py @@ -220,7 +220,7 @@ def test_losing(): """test losing boards""" losing_board = list('XXOO.....') - for i in range(10): + for _ in range(10): random.shuffle(losing_board) out = getoutput(f'{prg} -b {"".join(losing_board)}').splitlines() assert out[-1].strip() == 'No winner.' diff --git a/22_itictactoe/unit.py b/22_itictactoe/unit.py index 5544492e2..4b9e1466b 100755 --- a/22_itictactoe/unit.py +++ b/22_itictactoe/unit.py @@ -63,6 +63,6 @@ def test_losing(): losing_state = list('XXOO.....') - for i in range(10): + for _ in range(10): random.shuffle(losing_state) - assert find_winner(''.join(losing_state)) == None + assert find_winner(''.join(losing_state)) is None diff --git a/appendix_argparse/one_arg.py b/appendix_argparse/one_arg.py index 3c5328309..4ea555caa 100755 --- a/appendix_argparse/one_arg.py +++ b/appendix_argparse/one_arg.py @@ -22,7 +22,7 @@ def main(): """Make a jazz noise here""" args = get_args() - print('Hello, ' + args.name + '!') + print(f'Hello, {args.name}!') # -------------------------------------------------- diff --git a/bin/new.py b/bin/new.py index d8a3dcbf2..609f394cf 100755 --- a/bin/new.py +++ b/bin/new.py @@ -180,8 +180,7 @@ def get_defaults(): defaults = {} if os.path.isfile(rc): for line in open(rc): - match = re.match('([^=]+)=([^=]+)', line) - if match: + if match := re.match('([^=]+)=([^=]+)', line): key, val = map(str.strip, match.groups()) if key and val: defaults[key] = val diff --git a/extra/02_strings/test.py b/extra/02_strings/test.py index a124b4d07..4e1518cf0 100755 --- a/extra/02_strings/test.py +++ b/extra/02_strings/test.py @@ -74,7 +74,7 @@ def test_space(): word = random.choice([' ', '\t']) rv, out = getstatusoutput(f'{prg} "{word}"') assert rv == 0 - assert out == f'input is space.' + assert out == 'input is space.' # -------------------------------------------------- diff --git a/extra/07_proteins/test.py b/extra/07_proteins/test.py index 4cdb2d312..c4aa9a029 100755 --- a/extra/07_proteins/test.py +++ b/extra/07_proteins/test.py @@ -108,9 +108,12 @@ def run(input_seq, codons, expected): random_file = random_filename() try: flip = random.randint(0, 1) - out_file, out_arg = (random_file, - '-o ' + random_file) if flip == 1 else ('out.txt', - '') + out_file, out_arg = ( + (random_file, f'-o {random_file}') + if flip == 1 + else ('out.txt', '') + ) + print(f'{prg} -c {codons} {out_arg} {input_seq}') rv, output = getstatusoutput(f'{prg} -c {codons} {out_arg} {input_seq}') diff --git a/extra/09_moog/test.py b/extra/09_moog/test.py index 3c762de77..9a1761888 100755 --- a/extra/09_moog/test.py +++ b/extra/09_moog/test.py @@ -105,7 +105,7 @@ def test_defaults(): def test_options(): """runs on good input""" - out_file = random_string() + '.fasta' + out_file = f'{random_string()}.fasta' try: if os.path.isfile(out_file): os.remove(out_file) diff --git a/extra/10_whitmans/solution.py b/extra/10_whitmans/solution.py index b9969dd0c..93f5f0579 100755 --- a/extra/10_whitmans/solution.py +++ b/extra/10_whitmans/solution.py @@ -65,15 +65,14 @@ def main(): out_file = os.path.join(args.outdir, basename) print(f'{i:3}: {basename}') - out_fh = open(out_file, 'wt') - num_taken = 0 + with open(out_file, 'wt') as out_fh: + num_taken = 0 - for rec in SeqIO.parse(fh, 'fasta'): - if random.random() <= args.pct: - num_taken += 1 - SeqIO.write(rec, out_fh, 'fasta') + for rec in SeqIO.parse(fh, 'fasta'): + if random.random() <= args.pct: + num_taken += 1 + SeqIO.write(rec, out_fh, 'fasta') - out_fh.close() total_num += num_taken num_files = len(args.file) diff --git a/extra/10_whitmans/test.py b/extra/10_whitmans/test.py index 57d5a58a2..763e7af76 100755 --- a/extra/10_whitmans/test.py +++ b/extra/10_whitmans/test.py @@ -123,10 +123,10 @@ def test_options(): files = os.listdir(out_dir) assert len(files) == 3 - seqs_written = 0 - for file in files: - seqs_written += len( - list(SeqIO.parse(os.path.join(out_dir, file), 'fasta'))) + seqs_written = sum( + len(list(SeqIO.parse(os.path.join(out_dir, file), 'fasta'))) + for file in files + ) assert seqs_written == 27688 finally: