Skip to content

[Linting]: Lint practice stub files (8 / 8) #2809

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 29, 2021
Merged
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 exercises/practice/tournament/.meta/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def format_table(results):
table = ['Team | MP | W | D | L | P']

for team, games in sorted(
results.items(), key=lambda g: (-calculate_points(g[1]), g[0])):
results.items(), key=lambda group: (-calculate_points(group[1]), group[0])):
team_fmt = '{0:30} | {1:2} | {3:2} | {4:2} | {5:2} | {2:2}'
table.append(
team_fmt.format(team, sum(games), calculate_points(games), *games))
Expand Down
10 changes: 5 additions & 5 deletions exercises/practice/tree-building/.meta/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ def __init__(self, node_id):
self.children = []


def validateRecord(record):
def validate_record(record):
if record.equal_id() and record.record_id != 0:
raise ValueError("Only root should have equal record and parent id.")
raise ValueError('Only root should have equal record and parent id.')

if not record.equal_id() and record.parent_id >= record.record_id:
raise ValueError("Node record_id should be smaller than it's parent_id.")
Expand All @@ -24,10 +24,10 @@ def validateRecord(record):
def BuildTree(records):
parent_dict = {}
node_dict = {}
ordered_id = sorted((i.record_id for i in records))
ordered_id = sorted(idx.record_id for idx in records)

for record in records:
validateRecord(record)
validate_record(record)
parent_dict[record.record_id] = record.parent_id
node_dict[record.record_id] = Node(record.record_id)

Expand All @@ -36,7 +36,7 @@ def BuildTree(records):

for index, record_id in enumerate(ordered_id):
if index != record_id:
raise ValueError("Record id is invalid or out of order.")
raise ValueError('Record id is invalid or out of order.')

if record_id == root_id:
root = node_dict[record_id]
Expand Down
6 changes: 3 additions & 3 deletions exercises/practice/triangle/.meta/example.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
def valid(sides):
return sum(sorted(sides)[:2]) >= sorted(sides)[2] and all(
s > 0 for s in sides
side > 0 for side in sides
)


def equilateral(sides):
return valid(sides) and all(sides[0] == s for s in sides)
return valid(sides) and all(sides[0] == side for side in sides)


def isosceles(sides):
return valid(sides) and any(
s1 == s2 for s1, s2 in zip(sorted(sides), sorted(sides)[1:])
side_1 == side_2 for side_1, side_2 in zip(sorted(sides), sorted(sides)[1:])
)


Expand Down
6 changes: 3 additions & 3 deletions exercises/practice/trinary/.meta/example.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from functools import reduce


def trinary(s):
if set(s) - set('012'):
def trinary(string):
if set(string) - set('012'):
return 0
return reduce(lambda x, y: x * 3 + int(y), s, 0)
return reduce(lambda idx, edx: idx * 3 + int(edx), string, 0)
7 changes: 4 additions & 3 deletions exercises/practice/twelve-days/.meta/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@

def verse(day_number):
gifts = GIFTS[-day_number:]

if len(gifts) > 1:
gifts[:-1] = [', '.join(gifts[:-1])]

gifts = ', and '.join(gifts)
return 'On the {} day of Christmas my true love gave to me: {}.'.format(
ORDINAL[day_number], gifts)
return f'On the {ORDINAL[day_number]} day of Christmas my true love gave to me: {gifts}.'


def recite(start, end):
return [verse(n) for n in range(start, end + 1)]
return [verse(number) for number in range(start, end + 1)]
58 changes: 29 additions & 29 deletions exercises/practice/two-bucket/.meta/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,47 +7,47 @@

def measure(bucket_one, bucket_two, goal, start_bucket):
sizes = [bucket_one, bucket_two]
goalIndex = 0 if start_bucket == 'one' else 1
goal_index = 0 if start_bucket == 'one' else 1

def empty(buckets, i):
return [0, buckets[1]] if i == 0 else [buckets[0], 0]
def empty(buckets, idx):
return [0, buckets[1]] if idx == 0 else [buckets[0], 0]

def fill(buckets, i):
return [sizes[0], buckets[1]] if i == 0 else [buckets[0], sizes[1]]
def fill(buckets, idx):
return [sizes[0], buckets[1]] if idx == 0 else [buckets[0], sizes[1]]

def consolidate(buckets, i):
amount = min(buckets[1 - i], sizes[i] - buckets[i])
target = buckets[i] + amount
src = buckets[1 - i] - amount
return [target, src] if i == 0 else [src, target]
def consolidate(buckets, idx):
amount = min(buckets[1 - idx], sizes[idx] - buckets[idx])
target = buckets[idx] + amount
source = buckets[1 - idx] - amount
return [target, source] if idx == 0 else [source, target]

def bucket_str(buckets):
return '{},{}'.format(*buckets)
return f'{buckets[0]},{buckets[1]}'

invalid = [0, 0]
invalid[1 - goalIndex] = sizes[1 - goalIndex]
invalidStr = bucket_str(invalid)
invalid[1 - goal_index] = sizes[1 - goal_index]
invalid_string = bucket_str(invalid)
buckets = [0, 0]
buckets[goalIndex] = sizes[goalIndex]
toVisit = []
buckets[goal_index] = sizes[goal_index]
to_visit = []
visited = set()
count = 1
while goal not in buckets:
key = bucket_str(buckets)
if key != invalidStr and key not in visited:
if key != invalid_string and key not in visited:
visited.add(key)
nc = count + 1
for i in range(2):
if buckets[i] != 0:
toVisit.append((empty(buckets, i), nc))
if buckets[i] != sizes[i]:
toVisit.append((fill(buckets, i), nc))
toVisit.append((consolidate(buckets, i), nc))
if not any(toVisit):
number_count = count + 1
for idx in range(2):
if buckets[idx] != 0:
to_visit.append((empty(buckets, idx), number_count))
if buckets[idx] != sizes[idx]:
to_visit.append((fill(buckets, idx), number_count))
to_visit.append((consolidate(buckets, idx), number_count))
if not any(to_visit):
raise ValueError('No more moves!')
buckets, count = toVisit.pop(0)
buckets, count = to_visit.pop(0)

goalIndex = buckets.index(goal)
goalBucket = ['one', 'two'][goalIndex]
otherBucket = buckets[1 - goalIndex]
return (count, goalBucket, otherBucket)
goal_index = buckets.index(goal)
goal_bucket = ['one', 'two'][goal_index]
other_bucket = buckets[1 - goal_index]
return (count, goal_bucket, other_bucket)
4 changes: 2 additions & 2 deletions exercises/practice/two-fer/.meta/example.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
def two_fer(name=None):
return "One for {}, one for me.".format(name or 'you')
def two_fer(name='you'):
return f'One for {name}, one for me.'
40 changes: 20 additions & 20 deletions exercises/practice/variable-length-quantity/.meta/example.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,34 @@
EIGHTBITMASK = 0x80
SEVENBITSMASK = 0x7f
EIGHT_BIT_MASK = 0x80
SEVEN_BIT_MASK = 0x7f


def encode_single(n):
bytes_ = [n & SEVENBITSMASK]
n >>= 7
def encode_single(number):
byte_string = [number & SEVEN_BIT_MASK]
number >>= 7

while n > 0:
bytes_.append(n & SEVENBITSMASK | EIGHTBITMASK)
n >>= 7
while number > 0:
byte_string.append(number & SEVEN_BIT_MASK | EIGHT_BIT_MASK)
number >>= 7

return bytes_[::-1]
return byte_string[::-1]


def encode(numbers):
return sum((encode_single(n) for n in numbers), [])
return sum((encode_single(number) for number in numbers), [])


def decode(bytes_):
def decode(byte_string):
values = []
n = 0
number = 0

for i, byte in enumerate(bytes_):
n <<= 7
n += (byte & SEVENBITSMASK)
for idx, byte in enumerate(byte_string):
number <<= 7
number += (byte & SEVEN_BIT_MASK)

if byte & EIGHTBITMASK == 0:
values.append(n)
n = 0
elif i == len(bytes_) - 1:
raise ValueError("incomplete sequence")
if byte & EIGHT_BIT_MASK == 0:
values.append(number)
number = 0
elif idx == len(byte_string) - 1:
raise ValueError('incomplete sequence')

return values
1 change: 0 additions & 1 deletion exercises/practice/word-count/.meta/example.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import re

from collections import Counter


Expand Down
20 changes: 10 additions & 10 deletions exercises/practice/word-search/.meta/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ def __init__(self, x, y):
self.y = y

def __repr__(self):
return 'Point({}:{})'.format(self.x, self.y)
return f'Point({self.x}:{self.y})'

def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
Expand All @@ -19,7 +19,7 @@ def __eq__(self, other):
return self.x == other.x and self.y == other.y

def __ne__(self, other):
return not (self == other)
return not self == other


DIRECTIONS = (Point(1, 0), Point(1, -1), Point(1, 1), Point(-1, -1),
Expand All @@ -34,25 +34,25 @@ def __init__(self, puzzle):

def find_char(self, coordinate):
if coordinate.x < 0 or coordinate.x >= self.width:
return
return None
if coordinate.y < 0 or coordinate.y >= self.height:
return
return None
return self.rows[coordinate.y][coordinate.x]

def find(self, word, position, direction):
current = copy.copy(position)
for letter in word:
if self.find_char(current) != letter:
return
return None
current += direction
return position, current - direction

def search(self, word):
positions = (Point(x, y)
for x in range(self.width) for y in range(self.height))
for pos in positions:
for d in DIRECTIONS:
result = self.find(word, pos, d)
positions = (Point(idx, edx)
for idx in range(self.width) for edx in range(self.height))
for position in positions:
for direction in DIRECTIONS:
result = self.find(word, position, direction)
if result:
return result
return None
27 changes: 13 additions & 14 deletions exercises/practice/wordy/.meta/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,24 @@
from operator import floordiv as div


VALID_OPERATIONS = {"plus": add, "minus": sub,
"multiplied by": mul, "divided by": div}
VALID_OPERATIONS = {'plus': add, 'minus': sub, 'multiplied by': mul, 'divided by': div}


def answer(question):
if not bool(question[8:-1].strip().lower().split()):
raise ValueError("syntax error")
raise ValueError('syntax error')

elif not question.startswith("What is "):
raise ValueError("unknown operation")
elif not question.startswith('What is '):
raise ValueError('unknown operation')

else:
words = question[8:-1].strip().lower().split()
words.reverse()

try:
main_value = int(words.pop())
except ValueError:
raise ValueError("syntax error")
except ValueError as error:
raise ValueError('syntax error') from error

while words:
operation = [words.pop()]
Expand All @@ -29,22 +28,22 @@ def answer(question):
next_to_evaluate = words.pop()
second_value = int(next_to_evaluate)
break
except ValueError:
except ValueError as error:
if next_to_evaluate == operation[-1]:
raise ValueError("syntax error")
raise ValueError('syntax error') from error
else:
operation.append(next_to_evaluate)
else:
if operation[-1] not in VALID_OPERATIONS and not operation[-1].isdigit() :
raise ValueError("unknown operation")
raise ValueError('unknown operation')
else:
raise ValueError("syntax error")
raise ValueError('syntax error')

operation = " ".join(operation)
operation = ' '.join(operation)

try:
main_value = VALID_OPERATIONS[operation](main_value, second_value)
except KeyError:
raise ValueError("syntax error")
except KeyError as error:
raise ValueError('syntax error') from error

return main_value
20 changes: 10 additions & 10 deletions exercises/practice/yacht/.meta/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
CHOICE = 11


def sum_of_ns(number, dice):
return sum(n for n in dice if n == number)
def sum_of_numbers(number, dice):
return sum(idx for idx in dice if idx == number)


def full_house(dice):
Expand Down Expand Up @@ -44,12 +44,12 @@ def yacht(dice):

functions = [
yacht,
partial(sum_of_ns, 1),
partial(sum_of_ns, 2),
partial(sum_of_ns, 3),
partial(sum_of_ns, 4),
partial(sum_of_ns, 5),
partial(sum_of_ns, 6),
partial(sum_of_numbers, 1),
partial(sum_of_numbers, 2),
partial(sum_of_numbers, 3),
partial(sum_of_numbers, 4),
partial(sum_of_numbers, 5),
partial(sum_of_numbers, 6),
full_house,
four_of_a_kind,
little_straight,
Expand All @@ -61,5 +61,5 @@ def yacht(dice):
def score(dice, category):
try:
return functions[category](dice)
except IndexError:
raise ValueError("No such category.")
except IndexError as error:
raise ValueError('No such category.') from error
Loading