Skip to content

Commit 9c0a42d

Browse files
committed
fix bugs
1 parent 1d0eece commit 9c0a42d

18 files changed

+117
-480
lines changed

.vscode/launch.json

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
11
{
22
"version": "0.2.0",
33
"configurations": [
4+
{
5+
"name": "Python 调试程序: 当前文件",
6+
"type": "debugpy",
7+
"request": "launch",
8+
"program": "${file}",
9+
"console": "integratedTerminal"
10+
},
411
{
512
"name": "C/C++ Runner: Debug Session",
613
"type": "cppdbg",

.vscode/settings.json

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,5 +55,10 @@
5555
"C_Cpp_Runner.useLeakSanitizer": false,
5656
"C_Cpp_Runner.showCompilationTime": false,
5757
"C_Cpp_Runner.useLinkTimeOptimization": false,
58-
"C_Cpp_Runner.msvcSecureNoWarnings": false
58+
"C_Cpp_Runner.msvcSecureNoWarnings": false,
59+
"python.testing.pytestArgs": [
60+
"."
61+
],
62+
"python.testing.unittestEnabled": false,
63+
"python.testing.pytestEnabled": true
5964
}

8_puzzle.py

Lines changed: 52 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,32 @@
11
from queue import PriorityQueue
2+
from typing import List, Tuple, Optional, Set
23

34

45
class PuzzleState:
5-
def __init__(self, board, goal, moves=0, previous=None):
6-
self.board = board
7-
self.goal = goal
8-
self.moves = moves
9-
self.previous = previous
10-
11-
def __lt__(self, other):
6+
"""Represents a state in 8-puzzle solving with A* algorithm."""
7+
8+
def __init__(
9+
self,
10+
board: List[List[int]],
11+
goal: List[List[int]],
12+
moves: int = 0,
13+
previous: Optional["PuzzleState"] = None,
14+
) -> None:
15+
self.board = board # Current 3x3 board configuration
16+
self.goal = goal # Target 3x3 configuration
17+
self.moves = moves # Number of moves taken to reach here
18+
self.previous = previous # Previous state in solution path
19+
20+
def __lt__(self, other: "PuzzleState") -> bool:
21+
"""For PriorityQueue ordering: compare priorities."""
1222
return self.priority() < other.priority()
1323

14-
def priority(self):
24+
def priority(self) -> int:
25+
"""A* priority: moves + Manhattan distance."""
1526
return self.moves + self.manhattan()
1627

17-
def manhattan(self):
28+
def manhattan(self) -> int:
29+
"""Calculate Manhattan distance from current to goal state."""
1830
distance = 0
1931
for i in range(3):
2032
for j in range(3):
@@ -23,68 +35,66 @@ def manhattan(self):
2335
distance += abs(x - i) + abs(y - j)
2436
return distance
2537

26-
def is_goal(self):
38+
def is_goal(self) -> bool:
39+
"""Check if current state matches goal."""
2740
return self.board == self.goal
2841

29-
def neighbors(self):
42+
def neighbors(self) -> List["PuzzleState"]:
43+
"""Generate all valid neighboring states by moving empty tile (0)."""
3044
neighbors = []
3145
x, y = next((i, j) for i in range(3) for j in range(3) if self.board[i][j] == 0)
32-
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
33-
34-
for dx, dy in directions:
46+
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
3547
nx, ny = x + dx, y + dy
3648
if 0 <= nx < 3 and 0 <= ny < 3:
3749
new_board = [row[:] for row in self.board]
3850
new_board[x][y], new_board[nx][ny] = new_board[nx][ny], new_board[x][y]
3951
neighbors.append(
4052
PuzzleState(new_board, self.goal, self.moves + 1, self)
4153
)
42-
4354
return neighbors
4455

4556

46-
def solve_puzzle(initial_board, goal_board):
47-
initial_state = PuzzleState(initial_board, goal_board)
57+
def solve_puzzle(
58+
initial_board: List[List[int]], goal_board: List[List[int]]
59+
) -> Optional[PuzzleState]:
60+
"""
61+
Solve 8-puzzle using A* algorithm.
62+
63+
>>> solve_puzzle([[1,2,3],[4,0,5],[7,8,6]], [[1,2,3],[4,5,6],[7,8,0]]) is not None
64+
True
65+
"""
66+
initial = PuzzleState(initial_board, goal_board)
4867
frontier = PriorityQueue()
49-
frontier.put(initial_state)
50-
explored = set()
68+
frontier.put(initial)
69+
explored: Set[Tuple[Tuple[int, ...], ...]] = set()
5170

5271
while not frontier.empty():
53-
current_state = frontier.get()
54-
55-
if current_state.is_goal():
56-
return current_state
57-
58-
explored.add(tuple(map(tuple, current_state.board)))
59-
60-
for neighbor in current_state.neighbors():
72+
current = frontier.get()
73+
if current.is_goal():
74+
return current
75+
explored.add(tuple(map(tuple, current.board)))
76+
for neighbor in current.neighbors():
6177
if tuple(map(tuple, neighbor.board)) not in explored:
6278
frontier.put(neighbor)
63-
6479
return None
6580

6681

67-
def print_solution(solution):
82+
def print_solution(solution: Optional[PuzzleState]) -> None:
83+
"""Print step-by-step solution from initial to goal state."""
84+
if not solution:
85+
print("No solution found.")
86+
return
6887
steps = []
6988
while solution:
7089
steps.append(solution.board)
7190
solution = solution.previous
72-
steps.reverse()
73-
74-
for step in steps:
91+
for step in reversed(steps):
7592
for row in step:
7693
print(" ".join(map(str, row)))
7794
print()
7895

7996

80-
# Example usage
81-
initial_board = [[1, 2, 3], [4, 0, 5], [7, 8, 6]]
82-
83-
goal_board = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]
97+
if __name__ == "__main__":
98+
import doctest
8499

85-
solution = solve_puzzle(initial_board, goal_board)
86-
if solution:
87-
print("Solution found:")
88-
print_solution(solution)
89-
else:
90-
print("No solution found.")
100+
doctest.testmod(verbose=True)

Collatz Sequence/Collatz Sequence.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ def collatz_sequence(n):
99
steps.append(n)
1010
return steps
1111

12+
1213
# --- Main Program ---
1314
try:
1415
num = int(input("Enter a positive integer: "))

Task1.2.txt

Lines changed: 0 additions & 1 deletion
This file was deleted.

bank_managment_system/backend.py

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -43,16 +43,22 @@ def _get_last_acc_no(self):
4343

4444
# ----------------- Admin -----------------
4545
def check_admin(self, name, password):
46-
self.cur.execute("SELECT 1 FROM admin WHERE name=? AND pass=?", (name, password))
46+
self.cur.execute(
47+
"SELECT 1 FROM admin WHERE name=? AND pass=?", (name, password)
48+
)
4749
return self.cur.fetchone() is not None
4850

4951
# ----------------- Staff -----------------
5052
def create_employee(self, name, password, salary, position):
51-
self.cur.execute("INSERT INTO staff VALUES (?, ?, ?, ?)", (name, password, salary, position))
53+
self.cur.execute(
54+
"INSERT INTO staff VALUES (?, ?, ?, ?)", (name, password, salary, position)
55+
)
5256
self.conn.commit()
5357

5458
def check_employee(self, name, password):
55-
self.cur.execute("SELECT 1 FROM staff WHERE name=? AND pass=?", (name, password))
59+
self.cur.execute(
60+
"SELECT 1 FROM staff WHERE name=? AND pass=?", (name, password)
61+
)
5662
return self.cur.fetchone() is not None
5763

5864
def show_employees(self):
@@ -74,7 +80,7 @@ def create_customer(self, name, age, address, balance, acc_type, mobile_number):
7480
acc_no = self.acc_no
7581
self.cur.execute(
7682
"INSERT INTO bank VALUES (?, ?, ?, ?, ?, ?, ?)",
77-
(acc_no, name, age, address, balance, acc_type, mobile_number)
83+
(acc_no, name, age, address, balance, acc_type, mobile_number),
7884
)
7985
self.conn.commit()
8086
self.acc_no += 1
@@ -95,18 +101,24 @@ def get_detail(self, acc_no):
95101
def update_customer(self, field, new_value, acc_no):
96102
if field not in {"name", "age", "address", "mobile_number", "account_type"}:
97103
raise ValueError("Invalid customer field")
98-
self.cur.execute(f"UPDATE bank SET {field}=? WHERE acc_no=?", (new_value, acc_no))
104+
self.cur.execute(
105+
f"UPDATE bank SET {field}=? WHERE acc_no=?", (new_value, acc_no)
106+
)
99107
self.conn.commit()
100108

101109
def update_balance(self, amount, acc_no):
102-
self.cur.execute("UPDATE bank SET balance = balance + ? WHERE acc_no=?", (amount, acc_no))
110+
self.cur.execute(
111+
"UPDATE bank SET balance = balance + ? WHERE acc_no=?", (amount, acc_no)
112+
)
103113
self.conn.commit()
104114

105115
def deduct_balance(self, amount, acc_no):
106116
self.cur.execute("SELECT balance FROM bank WHERE acc_no=?", (acc_no,))
107117
bal = self.cur.fetchone()
108118
if bal and bal[0] >= amount:
109-
self.cur.execute("UPDATE bank SET balance=balance-? WHERE acc_no=?", (amount, acc_no))
119+
self.cur.execute(
120+
"UPDATE bank SET balance=balance-? WHERE acc_no=?", (amount, acc_no)
121+
)
110122
self.conn.commit()
111123
return True
112124
return False

binod.txt

Lines changed: 0 additions & 1 deletion
This file was deleted.

class.dat

157 Bytes
Binary file not shown.

news_oversimplifier.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111

1212

1313
def main():
14-
1514
# loads .env variables
1615
load_dotenv()
1716
API_KEY = os.getenv("NEWS_API_KEY")
@@ -23,13 +22,13 @@ def main():
2322
else:
2423
raise IndexError()
2524
except IndexError:
26-
sys.exit('Please provide correct number of command-line arguments')
25+
sys.exit("Please provide correct number of command-line arguments")
2726

2827
try:
2928
# get number of articles from user
3029
while True:
3130
try:
32-
num_articles = int(input('Enter number of articles: '))
31+
num_articles = int(input("Enter number of articles: "))
3332
break
3433
except ValueError:
3534
continue
@@ -40,28 +39,31 @@ def main():
4039
# output printing title, summary and no. of words in the summary
4140
for i, article in enumerate(articles):
4241
capitalized_title = capitalize_title(article["title"])
43-
print(f"\n{i+1}. {capitalized_title}")
42+
print(f"\n{i + 1}. {capitalized_title}")
4443

4544
content = article.get("content") or article.get("description") or ""
4645
if not content.strip():
4746
print("No content to oversimplify.")
4847
continue
4948

50-
summary = summarize_text(content) # returns summary
51-
count = word_count(summary) # returns word count
49+
summary = summarize_text(content) # returns summary
50+
count = word_count(summary) # returns word count
5251
print(f"\nOVERSIMPLIFIED:\n{summary}\n{count} words\n")
5352

5453
# ask user whether they want to save the output in a txt file
5554
while True:
56-
saving_status = input(
57-
"Would you like to save this in a text file? (y/n): ").strip().lower()
55+
saving_status = (
56+
input("Would you like to save this in a text file? (y/n): ")
57+
.strip()
58+
.lower()
59+
)
5860
if saving_status == "y":
5961
save_summary(article["title"], summary)
6062
break
6163
elif saving_status == "n":
6264
break
6365
else:
64-
print('Try again\n')
66+
print("Try again\n")
6567
continue
6668

6769
except Exception as e:
@@ -127,9 +129,7 @@ def fetch_news(api_key, query, max_articles=5): # no pytest
127129
raises:
128130
Exception: If the API response status is not 'ok'.
129131
"""
130-
url = (
131-
f"https://newsapi.org/v2/everything?q={query}&language=en&apiKey={api_key}&pageSize={max_articles}"
132-
)
132+
url = f"https://newsapi.org/v2/everything?q={query}&language=en&apiKey={api_key}&pageSize={max_articles}"
133133
response = requests.get(url)
134134
data = response.json()
135135
if data.get("status") != "ok":
@@ -147,8 +147,8 @@ def save_summary(title, summary, path="summaries.txt"): # no pytest
147147
path (str): File path to save the summary, i.e. 'summaries.txt'
148148
"""
149149
with open(path, "a", encoding="utf-8") as f:
150-
f.write(f"{title}\n{summary}\n{'='*60}\n")
150+
f.write(f"{title}\n{summary}\n{'=' * 60}\n")
151151

152152

153153
if __name__ == "__main__":
154-
main()
154+
main()

requirements.txt

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@ aiohttp
33
fuzzywuzzy
44
hupper
55
seaborn
6-
time
7-
simplegui
86
utils
97
Tubes
108
modules

0 commit comments

Comments
 (0)