Skip to content

Commit aab5177

Browse files
committed
feat(python): add leet code 140, 2109
1 parent 600f16b commit aab5177

File tree

9 files changed

+254
-111
lines changed

9 files changed

+254
-111
lines changed

check.sh

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
#!/bin/bash
2+
3+
# Find all directories containing "leet_code" folder
4+
roots=()
5+
for dir in */; do
6+
if [ -d "${dir}leet_code" ]; then
7+
roots+=("${dir%/}")
8+
fi
9+
done
10+
11+
if [ ${#roots[@]} -eq 0 ]; then
12+
echo "No directories containing 'leet_code' folder found."
13+
exit 1
14+
fi
15+
16+
# Create associative array to store all unique numeric filenames
17+
declare -A all_files
18+
# Create associative array to track which roots are missing which files
19+
declare -A missing_files
20+
21+
# First pass: collect all numeric filenames
22+
for root in "${roots[@]}"; do
23+
while IFS= read -r file; do
24+
# Extract basename without extension
25+
base=$(basename "$file")
26+
filename="${base%.*}"
27+
# Check if filename contains only digits
28+
if [[ $filename =~ ^[0-9]+$ ]]; then
29+
all_files[$filename]=1
30+
fi
31+
done < <(find "${root}/leet_code" -type f 2>/dev/null)
32+
done
33+
34+
# Second pass: check which files are missing from each root
35+
for filename in "${!all_files[@]}"; do
36+
missing=""
37+
for root in "${roots[@]}"; do
38+
# Check if any file with this numeric base exists (regardless of extension)
39+
if ! ls "${root}/leet_code/${filename}".* >/dev/null 2>&1; then
40+
if [ -z "$missing" ]; then
41+
missing="$root"
42+
else
43+
missing="$missing, $root"
44+
fi
45+
fi
46+
done
47+
if [ ! -z "$missing" ]; then
48+
missing_files[$filename]="$missing"
49+
fi
50+
done
51+
52+
# Output results
53+
if [ ${#missing_files[@]} -eq 0 ]; then
54+
echo "All roots contain the same numeric files."
55+
else
56+
echo "Missing files by root:"
57+
echo "----------------------"
58+
# Sort the filenames numerically
59+
while IFS= read -r filename; do
60+
if [ -n "${missing_files[$filename]}" ]; then
61+
echo "File $filename missing from: ${missing_files[$filename]}"
62+
fi
63+
done < <(printf "%s\n" "${!missing_files[@]}" | sort -n)
64+
fi

python/.idea/codeStyles/codeStyleConfig.xml

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

python/.idea/misc.xml

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

python/.idea/python.iml

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

python/.python-version

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
3.13

python/leet_code/140.py

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
"""Copyright ©2010-2024 <a href="https://github.com/jerodg/">JerodG</a>.
2+
3+
This program is free software: you can redistribute it and/or modify it under the terms of the
4+
Server Side Public License (SSPL) as published by MongoDB, Inc., either version 1 of the License,
5+
or (at your option) any later version.
6+
7+
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
8+
even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the SSPL
9+
for more details.
10+
11+
The above copyright notice and this permission notice shall be included in all copies or
12+
substantial portions of the Software. You should have received a copy of the SSPL along with this
13+
program. If not, see SSPL.
14+
"""
15+
import copy
16+
17+
18+
class TrieNode:
19+
"""A node in the Trie data structure used to store words."""
20+
21+
def __init__(self):
22+
"""Initializes a TrieNode with an empty dictionary for children and a boolean to mark the end of a word."""
23+
self.children = {}
24+
self.word = False
25+
26+
def add_word(self, word: str) -> None:
27+
"""
28+
Adds a word to the Trie.
29+
30+
Args:
31+
word (str): The word to be added to the Trie.
32+
"""
33+
cur = self
34+
for c in word:
35+
if c not in cur.children:
36+
cur.children[c] = TrieNode()
37+
cur = cur.children[c]
38+
cur.word = True
39+
40+
41+
class Solution:
42+
"""A class to solve the problem of word segmentation using a Trie and depth-first search."""
43+
44+
def wordBreak(self, s: str, word_dict: list[str]) -> list[str]:
45+
"""
46+
Finds all possible sentences that can be formed by segmenting the string `s` using words from `word_dict`.
47+
48+
Args:
49+
s (str): The input string to be segmented.
50+
word_dict (list[str]): A list of valid words for segmentation.
51+
52+
Returns:
53+
list[str]: A list of all possible sentences formed by valid segmentations.
54+
"""
55+
root = TrieNode()
56+
for w in word_dict:
57+
root.add_word(w)
58+
59+
res = []
60+
61+
def dfs(i: int, node: TrieNode, word: str, a: list[str], flag: bool = False) -> None:
62+
"""
63+
Performs depth-first search to find all valid segmentations.
64+
65+
Args:
66+
i (int): The current index in the string `s`.
67+
node (TrieNode): The current node in the Trie.
68+
word (str): The current word being formed.
69+
a (list[str]): The current list of words formed so far.
70+
flag (bool): A flag indicating if a valid word has been formed.
71+
"""
72+
if i == len(s):
73+
if flag:
74+
res.append(" ".join(a))
75+
return
76+
77+
if s[i] not in node.children:
78+
return
79+
80+
word += s[i]
81+
node = node.children[s[i]]
82+
83+
if node.word:
84+
a1 = copy.copy(a)
85+
a1.append(word)
86+
dfs(i + 1, root, '', a1, flag=True)
87+
88+
dfs(i + 1, node, word, a)
89+
90+
dfs(0, root, '', [])
91+
92+
return res

python/leet_code/2109.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""Copyright ©2010-2024 <a href="https://github.com/jerodg/">JerodG</a>.
2+
3+
This program is free software: you can redistribute it and/or modify it under the terms of the
4+
Server Side Public License (SSPL) as published by MongoDB, Inc., either version 1 of the License,
5+
or (at your option) any later version.
6+
7+
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
8+
even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the SSPL
9+
for more details.
10+
11+
The above copyright notice and this permission notice shall be included in all copies or
12+
substantial portions of the Software. You should have received a copy of the SSPL along with this
13+
program. If not, see SSPL.
14+
"""
15+
16+
17+
class Solution:
18+
"""A class to solve the problem of adding spaces at specified positions in a string."""
19+
20+
def addSpaces(self, s: str, spaces: List[int]) -> str:
21+
"""
22+
Inserts spaces into the string `s` at the positions specified in the list `spaces`.
23+
24+
Args:
25+
s (str): The input string where spaces need to be added.
26+
spaces (List[int]): A list of indices where spaces should be inserted.
27+
28+
Returns:
29+
str: The modified string with spaces inserted at the specified positions.
30+
"""
31+
index, result = 0, []
32+
33+
for space in spaces:
34+
# Append the substring from the current index to the space index
35+
result.append(s[index: space])
36+
# Update the index to the current space position
37+
index = space
38+
39+
# Append the remaining part of the string after the last space
40+
result.append(s[index:])
41+
42+
# Join all parts with a space and return the final string
43+
return ' '.join(result)

python/pyproject.toml

Lines changed: 8 additions & 105 deletions
Original file line numberDiff line numberDiff line change
@@ -1,109 +1,12 @@
11
[project]
2-
name = "python-code-challenges"
3-
version = "0.4.0"
4-
description = "Code Challenges"
2+
name = "python"
3+
version = "0.1.0"
4+
description = "Add your description here"
55
readme = "README.md"
6-
license-files = { paths = ["../LICENSE.adoc"] }
7-
requires-python = ">= 3.12"
8-
authors = [{ name = "JerodG", email = "[email protected]" }]
9-
dependencies = [
10-
]
11-
12-
13-
[build-system]
14-
requires = ["hatchling"]
15-
build-backend = "hatchling.build"
16-
17-
18-
[tool.rye]
19-
managed = true
20-
dev-dependencies = [
21-
"pytest>=8.0.2",
22-
"pytest-benchmark>=4.0.0",
23-
"pytest-cov>=4.1.0",
24-
]
25-
26-
27-
[[tool.rye.sources]]
28-
name = "default"
29-
url = "https://pypi.org/simple/"
30-
31-
32-
[tool.hatch.metadata]
33-
allow-direct-references = true
6+
requires-python = ">=3.13"
7+
dependencies = []
348

35-
36-
[tool.hatch.build.targets.wheel]
37-
packages = ["code_wars/", "hackerrank/", "leetcode/"]
38-
39-
40-
[tool.ruff]
41-
# Exclude a variety of commonly ignored directories.
42-
exclude = [
43-
".bzr",
44-
".direnv",
45-
".eggs",
46-
".git",
47-
".git-rewrite",
48-
".hg",
49-
".ipynb_checkpoints",
50-
".mypy_cache",
51-
".nox",
52-
".pants.d",
53-
".pyenv",
54-
".pytest_cache",
55-
".pytype",
56-
".ruff_cache",
57-
".svn",
58-
".tox",
59-
".venv",
60-
".vscode",
61-
"__pypackages__",
62-
"_build",
63-
"buck-out",
64-
"build",
65-
"dist",
66-
"node_modules",
67-
"site-packages",
68-
"venv",
69-
".idea",
70-
".venv"
9+
[dependency-groups]
10+
dev = [
11+
"ruff>=0.8.1",
7112
]
72-
73-
line-length = 120
74-
fix = true
75-
indent-width = 4
76-
target-version = "py312"
77-
include = ["*.py"]
78-
respect-gitignore = true
79-
80-
81-
82-
[tool.ruff.lint]
83-
# Enable Pyflakes (`F`) and a subset of the pycodestyle (`E`) codes by default.
84-
# Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or
85-
# McCabe complexity (`C901`) by default.
86-
select = ["E4", "E7", "E9", "F", "W", "C901", "C"]
87-
ignore = []
88-
preview = true
89-
task-tags = ["TODO", "FIXME"]
90-
# Allow fix for all enabled rules (when `--fix`) is provided.
91-
fixable = ["ALL"]
92-
unfixable = []
93-
# Allow unused variables when underscore-prefixed.
94-
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
95-
96-
[tool.ruff.format]
97-
quote-style = "single"
98-
indent-style = "space"
99-
skip-magic-trailing-comma = true
100-
line-ending = "lf"
101-
docstring-code-format = true
102-
docstring-code-line-length = 100
103-
104-
105-
[tool.pytest.ini_options]
106-
minversion = "6.0"
107-
addopts = "-ra -q"
108-
testpaths = ["tests"]
109-
markers = ["random: marks tests as random (deselect with '-m \"not random\"')"]

python/uv.lock

Lines changed: 39 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)