Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion 01_hello/hello04_argparse_positional.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}!')
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 9-9 refactored with the following changes:

2 changes: 1 addition & 1 deletion 01_hello/hello05_argparse_option.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}!')
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 10-10 refactored with the following changes:

2 changes: 1 addition & 1 deletion 01_hello/hello06_main_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}!')
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:


if __name__ == '__main__':
main()
2 changes: 1 addition & 1 deletion 01_hello/hello07_get_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def get_args():

def main():
args = get_args()
print('Hello, ' + args.name + '!')
print(f'Hello, {args.name}!')
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:


if __name__ == '__main__':
main()
2 changes: 1 addition & 1 deletion 01_hello/hello08_formatted.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def main():
"""Make a jazz noise here"""

args = get_args()
print('Hello, ' + args.name + '!')
print(f'Hello, {args.name}!')
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:



# --------------------------------------------------
Expand Down
2 changes: 1 addition & 1 deletion 03_picnic/solution.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]}'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:

bringing = ', '.join(items)

print('You are bringing {}.'.format(bringing))
Expand Down
4 changes: 1 addition & 3 deletions 04_jump_the_five/solution2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:

  • Use str.join() instead of for loop (use-join)

print(new_text)


Expand Down
4 changes: 1 addition & 3 deletions 04_jump_the_five/solution3.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:

print(''.join(new_text))


Expand Down
5 changes: 1 addition & 4 deletions 07_gashlycrumb/solution1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:

for letter in args.letter:
if letter.upper() in lookup:
print(lookup[letter.upper()])
Expand Down
14 changes: 8 additions & 6 deletions 11_bottles_of_beer/solution.py
Original file line number Diff line number Diff line change
Expand Up @@ -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!',
]
)
Comment on lines -46 to +53
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function verse refactored with the following changes:



# --------------------------------------------------
Expand Down
5 changes: 1 addition & 4 deletions 12_ransom/solution1_for_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:

print(''.join(ransom))


Expand Down
5 changes: 1 addition & 4 deletions 12_ransom/solution3_for_append_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:

  • Use str.join() instead of for loop (use-join)

print(''.join(ransom))


Expand Down
2 changes: 1 addition & 1 deletion 13_twelve_days/solution.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()}'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function verse refactored with the following changes:


return '\n'.join(lines)

Expand Down
2 changes: 1 addition & 1 deletion 13_twelve_days/solution_emoji.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()}'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function verse refactored with the following changes:


return '\n'.join(lines)

Expand Down
2 changes: 1 addition & 1 deletion 13_twelve_days/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function test_all refactored with the following changes:

assert out == ''
assert os.path.isfile(out_file)
output = open(out_file).read().rstrip()
Expand Down
20 changes: 8 additions & 12 deletions 14_rhymer/solution1_regex.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Comment on lines -47 to +57
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function stemmer refactored with the following changes:

This removes the following comments ( why? ):

# capture zero or more of anything



# --------------------------------------------------
Expand Down
6 changes: 3 additions & 3 deletions 14_rhymer/solution2_no_regex.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'))
):
Comment on lines -42 to +44
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function stemmer refactored with the following changes:

first_vowel = min(vowel_pos)
return (word[:first_vowel], word[first_vowel:])
else:
Expand Down
7 changes: 4 additions & 3 deletions 15_kentucky_friar/solution3_no_regex.py
Original file line number Diff line number Diff line change
Expand Up @@ -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] + "'"
Comment on lines -44 to +47
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function fry refactored with the following changes:


return word

Expand Down
2 changes: 1 addition & 1 deletion 15_kentucky_friar/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function run_file refactored with the following changes:


assert os.path.isfile(expected_file)
expected = open(expected_file).read()
Expand Down
2 changes: 1 addition & 1 deletion 17_mad_libs/solution2_no_regex.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:

had_placeholders = True

if had_placeholders:
Expand Down
3 changes: 1 addition & 2 deletions 19_wod/solution2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function read_csv refactored with the following changes:

low, high = map(int, match.groups())
exercises.append((name, low, high))

Expand Down
5 changes: 1 addition & 4 deletions 19_wod/using_csv1.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 8-11 refactored with the following changes:

pprint(records)
7 changes: 4 additions & 3 deletions 21_tictactoe/solution2.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
]
Comment on lines -72 to +75
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function format_board refactored with the following changes:


bar = '-------------'
cells_tmpl = '| {} | {} | {} |'
Expand Down
2 changes: 1 addition & 1 deletion 21_tictactoe/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ def test_losing():
"""test losing boards"""

losing_board = list('XXOO.....')
for i in range(10):
for _ in range(10):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function test_losing refactored with the following changes:

random.shuffle(losing_board)
out = getoutput(f'{prg} -b {"".join(losing_board)}').splitlines()
assert out[-1].strip() == 'No winner.'
4 changes: 2 additions & 2 deletions 22_itictactoe/unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Comment on lines -66 to +68
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function test_losing refactored with the following changes:

2 changes: 1 addition & 1 deletion appendix_argparse/one_arg.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def main():
"""Make a jazz noise here"""

args = get_args()
print('Hello, ' + args.name + '!')
print(f'Hello, {args.name}!')
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:



# --------------------------------------------------
Expand Down
3 changes: 1 addition & 2 deletions bin/new.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function get_defaults refactored with the following changes:

key, val = map(str.strip, match.groups())
if key and val:
defaults[key] = val
Expand Down
2 changes: 1 addition & 1 deletion extra/02_strings/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function test_space refactored with the following changes:



# --------------------------------------------------
Expand Down
9 changes: 6 additions & 3 deletions extra/07_proteins/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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', '')
)

Comment on lines -111 to +116
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function run refactored with the following changes:

print(f'{prg} -c {codons} {out_arg} {input_seq}')
rv, output = getstatusoutput(f'{prg} -c {codons} {out_arg} {input_seq}')

Expand Down
2 changes: 1 addition & 1 deletion extra/09_moog/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function test_options refactored with the following changes:

try:
if os.path.isfile(out_file):
os.remove(out_file)
Expand Down
13 changes: 6 additions & 7 deletions extra/10_whitmans/solution.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Comment on lines -68 to -76
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main refactored with the following changes:

total_num += num_taken

num_files = len(args.file)
Expand Down
8 changes: 4 additions & 4 deletions extra/10_whitmans/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Comment on lines -126 to +129
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function test_options refactored with the following changes:


assert seqs_written == 27688
finally:
Expand Down