Skip to content

Commit

Permalink
Improve code quality
Browse files Browse the repository at this point in the history
  • Loading branch information
Sigmanificient committed Apr 21, 2024
1 parent bc9e0d9 commit 887ae7f
Show file tree
Hide file tree
Showing 80 changed files with 461 additions and 370 deletions.
9 changes: 4 additions & 5 deletions scripts/auto_update_readme.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@


challenges: Dict[str, List[str]] = {}
difficulties: Dict[int, List[int]] = {i: [] for i in range(9)}
difficulties: Dict[int, List[str]] = {i: [] for i in range(9)}
counts: Dict[int, int] = {}
total: int = 0

Expand Down Expand Up @@ -87,8 +87,7 @@
for ext in challenges[filename]
)

f.write(
f"\n" f"`{filename.replace('_', ' ').capitalize()}`:\n" f"{icons}\n"
)
clean_filename = filename.replace('_', ' ').capitalize()
f.write(f"\n" f"`{clean_filename}`:\n"{icons}\n")

f.write("</details>\n")
f.write("</details>\n")
5 changes: 2 additions & 3 deletions src/python/katas/beta/async_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
from itertools import cycle
from random import randint
from string import ascii_letters
from time import perf_counter

_cycler = cycle(ascii_letters)

Expand All @@ -25,5 +24,5 @@ def run_it(n: int) -> str:

for _ in range(5):
rand = randint(14, 300)
s = "".join(next(_cycler_copy) for i in range(rand))
assert run_it(rand) == s
s = "".join(next(_cycler_copy) for _ in range(rand))
assert run_it(rand) == s
4 changes: 2 additions & 2 deletions src/python/katas/beta/rgb_colour_changer.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Kata url: https://www.codewars.com/kata/62e27045c0d7a04c846874d2."""


def colour_changer(rgb: str, percent: int = 10) -> str:
def colour_changer(rgb: str, percent: int | float = 10) -> str:
out = [
round((c := int(rgb[i + 1 : i + 3], 16)) - (c * (percent / 100)))
for i in range(0, len(rgb) - 1, 2)
Expand Down Expand Up @@ -29,4 +29,4 @@ def test_colour_changer():
assert colour_changer("#A1B2C8") == "#91a0b4"

assert colour_changer("#abc123", 10) in ["#9aae20", "#9aae1f"]
assert colour_changer("#aBc123", 10) in ["#9aae20", "#9aae1f"]
assert colour_changer("#aBc123", 10) in ["#9aae20", "#9aae1f"]
41 changes: 21 additions & 20 deletions src/python/katas/py2kyu/evaluate_a_mathematical_expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,27 +96,28 @@ def integer(self):
return digits

def get_next_token(self):
while self.current_char is not None:
self.skip_whitespace()
if (
self.current_char == '-'
and self.previous_char in '+-*/('
):
self.advance()
return Token(TokenType.MINUS, self.previous_char)
if self.current_char is None:
return Token(TokenType.END_OF_FILE)

if self.current_char.isdigit():
return Token(TokenType.INTEGER, self.integer())
self.skip_whitespace()
if (
self.current_char == '-'
and self.previous_char is not None
and self.previous_char in '+-*/('
):
self.advance()
return Token(TokenType.MINUS, self.previous_char)

token = self.char_tokens.get(self.current_char)
if self.current_char.isdigit():
return Token(TokenType.INTEGER, self.integer())

if token is None:
raise InvalidCharacter(self.current_char)
token = self.char_tokens.get(self.current_char)
if token is None:
raise InvalidCharacter(self.current_char)

self.advance()
return Token(token, self.previous_char)
self.advance()
return Token(token, self.previous_char)

return Token(TokenType.END_OF_FILE)


class AST:
Expand Down Expand Up @@ -262,12 +263,12 @@ def visit_bin_op(self, node):
self.visit(node.right)
)

def interpret(self) -> int:
def interpret(self) -> int | float:
tree = self.parser.parse()
return self.visit(tree)


def calc(expression):
def calc(expression) -> int | float:
lexer = Lexer(expression)
parser = Parser(lexer)
interpreter = Interpreter(parser)
Expand All @@ -277,7 +278,7 @@ def calc(expression):

def test_calc():
assert calc('1 + 1') == 2
assert calc('8/16') == 0.5
assert (calc('8/16') - 0.5) < 0.0001
assert calc('3 -(-1)') == 4
assert calc('2 + -2') == 0
assert calc('10- 2- -5') == 13
Expand All @@ -291,4 +292,4 @@ def test_calc():

for char in 'abcd%!:,.':
with pytest.raises(InvalidCharacter):
calc(char)
calc(char)
47 changes: 25 additions & 22 deletions src/python/katas/py2kyu/game_of_go.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,20 @@
"""Kata url: https://www.codewars.com/kata/59de9f8ff703c4891900005c"""
import pytest

X_LABELS = 'ABCDEFGHJKLMNOPQRSTUVWXYZ'
Y_LABELS = list(map(str, range(1, 26)))

EMPTY = '.'
PLAYER_SYMBOLS = 'xo'
HANDICAP_STONES = {
9: [(6, 2), (2, 6), (6, 6), (2, 2), (4, 4)],
13: [(9, 3), (3, 9), (9, 9), (3, 3), (6, 6), (3, 6), (9, 6), (6, 3), (6, 9)],
19: [(15, 3), (3, 15), (15, 15), (3, 3), (9, 9), (3, 9), (15, 9), (9, 3), (9, 15)]
}


class Go:
EMPTY = '.'
X_LABELS = 'ABCDEFGHJKLMNOPQRSTUVWXYZ'
Y_LABELS = list(map(str, range(1, 26)))
PLAYER_SYMBOLS = 'xo'
HANDICAP_STONES = {
9: [(6, 2), (2, 6), (6, 6), (2, 2), (4, 4)],
13: [(9, 3), (3, 9), (9, 9), (3, 3), (6, 6), (3, 6), (9, 6), (6, 3), (6, 9)],
19: [(15, 3), (3, 15), (15, 15), (3, 3), (9, 9), (3, 9), (15, 9), (9, 3), (9, 15)]
}


def __init__(self, height, width=0):
if not width:
Expand All @@ -26,12 +29,12 @@ def __init__(self, height, width=0):
self.width = width
self.height = height

self.board = [[self.EMPTY for _ in range(width)] for _ in range(height)]
self.board = [[EMPTY for _ in range(width)] for _ in range(height)]
self.history = []
self.__save_state()

self.y_labels = self.Y_LABELS[:height][::-1]
self.x_labels = self.X_LABELS[:width]
self.y_labels = Y_LABELS[:height][::-1]
self.x_labels = X_LABELS[:width]
self.handicap = False
self.__turn = 0

Expand All @@ -49,7 +52,7 @@ def __next_turn(self):

def __handle_capture(self, y, x, is_self=False):
stone = self.board[y][x]
if stone == self.EMPTY:
if stone == EMPTY:
return

if stone == self.current and not is_self:
Expand All @@ -58,7 +61,7 @@ def __handle_capture(self, y, x, is_self=False):
if self.__get_liberties_count(y, x):
return

self.board[y][x] = self.EMPTY
self.board[y][x] = EMPTY

if is_self:
raise ValueError('Self capturing is illegal')
Expand All @@ -68,18 +71,18 @@ def __handle_capture(self, y, x, is_self=False):
def __remove_group(self, y, x):
for nx, ny in self.__get_neighbors(y, x):
neighbor = self.board[ny][nx]
if neighbor == self.EMPTY:
if neighbor == EMPTY:
continue

if neighbor == self.current:
continue

self.board[ny][nx] = self.EMPTY
self.board[ny][nx] = EMPTY
self.__remove_group(ny, nx)

def __get_liberties_count(self, y, x, group=None):
stone = self.board[y][x]
if stone == self.EMPTY:
if stone == EMPTY:
return 0

if group is None:
Expand All @@ -89,7 +92,7 @@ def __get_liberties_count(self, y, x, group=None):
for nx, ny in self.__get_neighbors(y, x, group):
neighbor = self.board[ny][nx]

if neighbor == self.EMPTY:
if neighbor == EMPTY:
liberties += 1

if neighbor == stone:
Expand Down Expand Up @@ -129,7 +132,7 @@ def move(self, *player_moves):
if self.board[y][x] != '.' and (y != 5 and x != 2):
raise ValueError('Invalid move, already assigned')

self.board[y][x] = self.PLAYER_SYMBOLS[self.__turn]
self.board[y][x] = PLAYER_SYMBOLS[self.__turn]

for nx, ny in self.__get_neighbors(y, x):
self.__handle_capture(ny, nx)
Expand All @@ -153,7 +156,7 @@ def handicap_stones(self, amount):
if len(self.history) > 1:
raise ValueError('Handicap cannot be set after the first move')

placements = self.HANDICAP_STONES.get(self.width)
placements = HANDICAP_STONES.get(self.width)
if not placements:
raise ValueError('Cannot put handicap stone')

Expand Down Expand Up @@ -195,7 +198,7 @@ def turn(self):

@property
def current(self):
return self.PLAYER_SYMBOLS[self.__turn]
return PLAYER_SYMBOLS[self.__turn]



Expand Down Expand Up @@ -400,4 +403,4 @@ def test_go():
[".", ".", ".", ".", ".", ".", ".", ".", "."]
]

assert game.turn == "black"
assert game.turn == "black"
6 changes: 3 additions & 3 deletions src/python/katas/py3kyu/the_builder_of_things.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@
class Func:
def __init__(self, func, ins):
self.ins = ins
self.func = func
self.function = func
self.func_outs = []

def __call__(self, *args, **kwargs):
r = self.func(*args, **kwargs)
r = self.function(*args, **kwargs)

self.func_outs.append(r)
return r
Expand Down Expand Up @@ -230,4 +230,4 @@ def fnc(phrase):

assert jane.spoke == ["Jane says: hi"]
jane.speak("goodbye")
assert jane.spoke == ["Jane says: hi", "Jane says: goodbye"]
assert jane.spoke == ["Jane says: hi", "Jane says: goodbye"]
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
def recover_secret(triplets) -> str:
data = defaultdict(int)

for i in range(len(triplets)):
for _ in range(len(triplets)):
for a, b, c in triplets:

if data[a] >= data[b]:
Expand All @@ -28,4 +28,4 @@ def test_recover_string():
['t', 'i', 's'],
['w', 'h', 's']
]
) == "whatisup"
) == "whatisup"
11 changes: 8 additions & 3 deletions src/python/katas/py4kyu/the_observed_pin.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
"""Kata url: https://www.codewars.com/kata/5263c6999e0f40dee200059d."""


def get_pins(observed):
each_comb = []
def get_pin_combinations(observed):
layout = "123456789 0 "
each_comb = []

for o_digit in observed:
i = layout.index(o_digit)
Expand All @@ -27,6 +27,11 @@ def get_pins(observed):
neighbours.append(v)

each_comb.append(neighbours + [o_digit])
return each_comb


def get_pins(observed):
each_comb = get_pin_combinations(observed)

out = []
comb_length = [len(l) for l in each_comb]
Expand Down Expand Up @@ -130,4 +135,4 @@ def test_get_pins():
"477",
"478",
]
)
)
3 changes: 1 addition & 2 deletions src/python/katas/py5kyu/bird_mountains.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@


def peak_height(mountain: List[str]) -> int:
# TODO: optimize this in O(n²)
old = []
out = [[-1 for _i in range(len(mountain[0]))] for _j in range(len(mountain))]

Expand Down Expand Up @@ -57,4 +56,4 @@ def test_peak_height():

assert peak_height([" ", " ", " "]) == 0

assert peak_height(mountain=["^" * 21 for _ in range(21)]) == 11
assert peak_height(mountain=["^" * 21 for _ in range(21)]) == 11
Loading

0 comments on commit 887ae7f

Please sign in to comment.